Move the first and last items to a list

How can I swap the list?

For instance:

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

I would like to change 12 to 5 .

Is there a built-in Python function that allows me to do this?

+4
source share
6 answers
 >>> lis = [5,6,7,10,11,12] >>> lis[0], lis[-1] = lis[-1], lis[0] >>> lis [12, 6, 7, 10, 11, 5] 

The procedure for evaluating the above expression:

 expr3, expr4 = expr1, expr2 

The first elements in the RHS are assembled in a tuple, and then the tuple is unpacked and assigned to the LHS elements.

 >>> 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] 
+17
source

you can change this code,

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

You can use the 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 more here .

+1
source

Use the index of the number you want to change.

 In [38]: t = [5,6,7,10,11,12] In [40]: index5 = t.index(5) # grab the index of the first element that equals 5 In [41]: index12 = t.index(12) # grab the index of the first element that equals 12 In [42]: t[index5], t[index12] = 12, 5 # swap the values In [44]: t Out[44]: [12, 6, 7, 10, 11, 5] 

Then you can execute the quick change function

 def swapNumbersInList( listOfNums, numA, numB ): indexA = listOfNums.index(numA) indexB = listOfNums.index(numB) listOfNums[indexA], listOfNums[indexB] = numB, numA # calling the function swapNumbersInList([5,6,7,10,11,12], 5, 12) 
0
source

Another way (not very cute):

 mylist = [5, 6, 7, 10, 11, 12] first_el = mylist.pop(0) # first_el = 5, mylist = [6, 7, 10, 11, 12] last_el = mylist.pop(-1) # last_el = 12, mylist = [6, 7, 10, 11] mylist.insert(0, last_el) # mylist = [12, 6, 7, 10, 11] mylist.append(first_el) # mylist = [12, 6, 7, 10, 11, 5] 
0
source
 array = [5,2,3,6,1,12] temp = '' lastvalue = 5 temp = array[0] array[0] = array[lastvalue] array[lastvalue] = temp print(array) 

Hope this helps :)

0
source

All Articles