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?
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.
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.
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.
>>> 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_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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With