Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping first and last items in a list

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?

like image 296
user2891763 Avatar asked Oct 29 '13 18:10

user2891763


People also ask

How do you swap the first and last elements of a list argument?

Approach #5: Swap the first and last elements is to use the inbuilt function list. pop(). Pop the first element and store it in a variable. Similarly, pop the last element and store it in another variable.

How do you switch two items in a list in Python?

To swap two list elements x and y by value, get the index of their first occurrences using the list. index(x) and list. index(y) methods and assign the result to variables i and j , respectively. Then apply the multiple assignment expression lst[i], lst[j] = lst[j], lst[i] to swap the elements.

Can you swap items in a list Python?

Use the pop() Function to Swap Elements of a List in Python. The pop() function with a list removes and returns the value from a specified index. In the following code, we have popped two elements from the list using their index and stored the returned values into two variables.


3 Answers

>>> 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]
like image 193
Ashwini Chaudhary Avatar answered Oct 20 '22 19:10

Ashwini Chaudhary


you can swap using this code,

list[0],list[-1] = list[-1],list[0]
like image 43
Ashif Abdulrahman Avatar answered Oct 20 '22 19:10

Ashif Abdulrahman


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.

like image 45
aghd Avatar answered Oct 20 '22 20:10

aghd