Swapping first and last items in a list Swapping first and last items in a list python-3.x python-3.x

Swapping first and last items in a list


>>> 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]


you can swap using this code,

list[0],list[-1] = list[-1],list[0]


You can use "*" operator.

my_list = [1,2,3,4,5,6,7,8,9]a, *middle, b = my_listmy_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.