Swapping first and last items in a list

31,626

Solution 1

>>> lis = [5,6,7,10,11,12]
>>> lis[0], lis[-1] = lis[-1], lis[0]
>>> lis
[12, 6, 7, 10, 11, 5]

Order of evaluation of the above expression:

expr3, expr4 = expr1, expr2

First items on RHS are collected in a tuple, and then that tuple is unpacked and assigned to the items on the LHS.

>>> lis = [5,6,7,10,11,12]
>>> tup = lis[-1], lis[0]
>>> tup
(12, 5)
>>> lis[0], lis[-1] = tup
>>> lis
[12, 6, 7, 10, 11, 5]

Solution 2

You can use "*" operator.

my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]

Read here for more information.

Solution 3

you can swap using this code,

list[0],list[-1] = list[-1],list[0]
Share:
31,626
user2891763
Author by

user2891763

Updated on July 09, 2022

Comments

  • user2891763
    user2891763 almost 2 years

    How can I go about swapping numbers in a given list?

    For example:

    list = [5,6,7,10,11,12]
    

    I would like to swap 12 with 5.

    Is there an built-in Python function that can allow me to do that?

    • DSM
      DSM over 10 years
      What specifies which elements you want to swap? The values (replace every 12 with a 5 and every 5 with a 12), the positions (switch the values in the first and last place), or some other rule? For example, what do you want to happen for [5,5,12,12]?
    • user2891763
      user2891763 over 10 years
      I would like the last number in the list to always be swapped with the first number in a list.... in any given list.
  • user2891763
    user2891763 over 10 years
    hello ! Thanks for the prompt reply ! Could you please explain what is happening in this piece of Code... I am fairly new at programming.
  • Ashwini Chaudhary
    Ashwini Chaudhary over 10 years
    @user2891763 I've added some explanation.
  • truthadjustr
    truthadjustr almost 3 years
    This swapping technique also works for numpy.ndarray
  • truthadjustr
    truthadjustr almost 3 years
    Yes. Also works the same for numpy.ndarray