Open In App

Python - Move Element to End of the List

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list we need to move particular element to end to the list. For example, we are given a list a=[1,2,3,4,5] we need to move element 3 at the end of the list so that output list becomes [1, 2, 4, 5, 3].

Using remove() and append()

We can remove the element from its current position and then append it to the end of list.

Python
a = [1, 2, 3, 4, 5]
ele = 3

a.remove(ele)  # Remove the element
a.append(ele)  # Append it to the end

print(a)  

Output
[1, 2, 4, 5, 3]

Explanation:

  • remove(ele) method removes the first occurrence of the element 3 from the list a.
  • append(ele) method adds the element 3 to the end of list so the final list becomes [1, 2, 4, 5, 3].

Using pop() and append()

We can use pop() to remove the element by its value or index and then append it to the end.

Python
a = [1, 2, 3, 4, 5]
ele = 3

a.pop(a.index(ele))  # Remove the element by index
a.append(ele)  # Append it to the end

print(a)  

Output
[1, 2, 4, 5, 3]

Explanation:

  • pop(a.index(ele)) method finds the index of the element 3 using a.index(ele) and removes it from list a by using pop(index).
  • append(ele) method adds the element 3 to the end of the list, so the final list becomes [1, 2, 4, 5, 3]

Using List Comprehension

This method uses list comprehension to recreate list moving the element to end.

Python
a = [1, 2, 3, 4, 5]
ele = 3

a = [x for x in a if x != ele] + [ele]  # Move element to the end

print(a) 

Output
[1, 2, 4, 5, 3]

Explanation:

  • List comprehension [x for x in a if x != ele] creates a new list with all elements of a except for 3.
  • Expression + [ele] adds element 3 to the end of the new list, resulting in [1, 2, 4, 5, 3]

Using index()

We can find element's index and use slicing to create a new list placing the element at end.

Python
a = [1, 2, 3, 4, 5]
ele = 3

idx = a.index(ele)  # Find the index of the element
a = a[:idx] + a[idx+1:] + [ele]  # Use slicing to place the element at the end

print(a) 

Output
[1, 2, 4, 5, 3]

Explanation:

  • a.index(ele) method finds the index of element 3 in the list a.
  • Expression a[:idx] + a[idx+1:] + [ele] uses slicing to create a new list excluding the element 3 from its original position and then appending it to end of list.

Next Article
Practice Tags :

Similar Reads