Python | Move element to end of the list
The manipulation of lists is quite common in day-day programming. One can come across various issues where one wishes to perform using just one-liners. One such problem can be of moving a list element to the rear ( end of list ). Let’s discuss certain ways in which this can be done.
Method #1 : Using append() + pop() + index()
This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.
# Python3 code to demonstrate # moving element to end # using append() + pop() + index() # initializing list test_list = ['3', '5', '7', '9', '11'] # printing original list print ("The original list is : " + str(test_list)) # using append() + pop() + index() # moving element to end test_list.append(test_list.pop(test_list.index(5))) # printing result print ("The modified element moved list is : " + str(test_list)) |
The original list is : ['3', '5', '7', '9', '11'] The modified element moved list is : ['3', '7', '9', '11', '5']
Method #2 : Using sort() + key = (__eq__)
The sort method can also be used to achieve this particular task in which we provide the key as equal to the string we wish to shift so that it is moved to the end.
# Python3 code to demonstrate # moving element to end # using sort() + key = (__eq__) # initializing list test_list = ['3', '5', '7', '9', '11'] # printing original list print ("The original list is : " + str(test_list)) # using sort() + key = (__eq__) # moving element to end test_list.sort(key = '5'.__eq__) # printing result print ("The modified element moved list is : " + str(test_list)) |
The original list is : ['3', '5', '7', '9', '11'] The modified element moved list is : ['3', '7', '9', '11', '5']
Recommended Posts:
- Python | Move one list element to another list
- Move all zeroes to end of array using List Comprehension in Python
- Python | Replace elements in second list with index of same element in first list
- Python | Indices list of matching element from other list
- Python | Slicing list from Kth element to last element
- Python | How to get the last element of list
- Python | Three element sum in list
- Python | Element repetition in list
- Python | Operation to each element in list
- Python | Operate on every Kth element of list
- Python | Removing first element of list
- Python | Remove given element from the list
- Python | Insert after every Nth element in a list
- Python | Last occurrence of some element in a list
- Python | Add the element in the list with help of indexing
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



