Open In App

Python | Move element to end of the list

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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 (& quot
        The original list is : & quot
        + str(test_list))
 
# using append() + pop() + index()
# moving element to end
test_list.append(test_list.pop(test_list.index(5)))
 
# printing result
print (& quot
        The modified element moved list is : & quot
        + str(test_list))


Output : 

The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

  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




# 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 (& quot
        The original list is : & quot
        + str(test_list))
 
# using sort() + key = (__eq__)
# moving element to end
test_list.sort(key='5'.__eq__)
 
# printing result
print (& quot
        The modified element moved list is : & quot
        + str(test_list))


Output : 

The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']

Method #3 : Using remove() and insert() methods

Python3




# Python3 code to demonstrate
# moving element to end
 
# initializing list
test_list = ['3', '5', '7', '9', '11']
 
# printing original list
print("The original list is : " + str(test_list))
x = len(test_list)
test_list.remove('5')
test_list.insert(x-1, '5')
 
# printing result
print("The modified element moved list is : " + str(test_list))


Output

The original list is : ['3', '5', '7', '9', '11']
The modified element moved list is : ['3', '7', '9', '11', '5']

Method #4 : Using list comprehension

Python3




def move_to_end(lst, elem):
  #moving to end
  lst = [x for x in lst if x != elem] + [elem]
  return lst
 
#Test the function
lst = [1, 2, 3, 4, 5]
elem = 3
print(move_to_end(lst, elem)) # should print [1, 2, 4, 5, 3]
#This code is contributed by Edula Vinay Kumar Reddy


Output

[1, 2, 4, 5, 3]

Time complexity: O(n)

Auxiliary Space: O(n)

Method #4 : Using del and ‘+’ operator

Python3




# Define a list of string elements
test_list = ['3', '5', '7', '9', '11']
 
# Define the element that needs to be updated
element = '5'
 
# Find the index of the element in the list using the index() method
i = test_list.index(element)
 
# Delete the element at the found index using the del keyword
del test_list[i]
 
# Add the updated element to the list using concatenation
test_list = test_list + [element]
 
# Print the updated list
print(test_list)
#this code is contributed by Asif_Shaik


Output

['3', '7', '9', '11', '5']

Step-by-step algorithm:

  1. Initialize the list test_list with the given input.
  2. Assign the value element to the variable element.
  3. Use the index() method to find the index of the element in the list that matches element. Assign the resulting index to the variable i.
  4. Use the del keyword to remove the element at the index i from the list.
  5. Use concatenation to add the updated element to the list.
  6. Assign the updated list to the variable test_list.
  7. Print the updated list.

Time complexity:
The time complexity of the algorithm is O(n), where n is the length of the input list test_list. The index() method has a linear time complexity with respect to the length of the list. The concatenation operation also has a linear time complexity with respect to the length of the list.

Auxiliary space complexity:
The auxiliary space complexity of the algorithm is O(1), constant. This is because the algorithm only creates a few variables to store the input list, the element to be updated, and the updated list. The size of these variables is independent of the size of the input list. Therefore, the space complexity of the algorithm is constant.

here’s an approach using collections.deque.rotate():

The collections.deque class in Python provides a rotate() method, which can be used to move elements in a list. We can convert our list into a deque, rotate it to move the desired element to the end, and then convert it back into a list.

Algorithm:

Initialize the list and the element to be moved.
Convert the list to a deque using the collections.deque method.
Find the index of the element using the index() method.
Rotate the deque by the number of steps needed to move the element to the end using the rotate() method.
Convert the deque back to a list using the list() method.
Print the modified list.

Python3




import collections
 
# initializing list
test_list = ['3', '5', '7', '9', '11']
# element to be moved
elem = '5'
 
# converting list to deque
deq_list = collections.deque(test_list)
 
# finding the index of the element
idx = deq_list.index(elem)
 
# rotating the deque by the number of steps to move element to the end
deq_list.rotate(-idx - 1)
 
# converting deque back to list
test_list = list(deq_list)
 
# printing the modified list
print("The modified element moved list is :", test_list)


Output

The modified element moved list is : ['7', '9', '11', '3', '5']

Method #5: Using ITERATION and a temporary variable

In this method, we iterate through the list and keep track of the element to be moved to the end using a temporary variable. Once we reach the end of the list, we append the temporary variable to the list.

Algorithm:

Initialize a variable ‘temp’ to the element to be moved to the end.
Iterate through the list.
If the current element is not equal to the element to be moved, append it to a new list.
Once the end of the list is reached, append the ‘temp’ variable to the new list.
Return the new list.
 

Python3




def move_to_end(lst, elem):
    new_lst = []
    temp = None
    for i in lst:
        if i != elem:
            new_lst.append(i)
        else:
            temp = i
    new_lst.append(temp)
    return new_lst
 
# Test the function
lst = [1, 2, 3, 4, 5]
elem = 3
print(move_to_end(lst, elem)) # should print [1, 2, 4, 5, 3]


Output

[1, 2, 4, 5, 3]

Time complexity:
The time complexity of this algorithm is O(n), where n is the length of the list.

Auxiliary Space:
The space complexity of this algorithm is O(n), where n is the length of the list, as we are creating a new list to store the modified elements.



Last Updated : 02 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads