Python - Print list after removing element at given index
Last Updated : 15 Jan, 2025
Improve
In this article, we will explore different ways to remove an element from a list at a given index and print the updated list, offering multiple approaches for achieving this.
Using pop()
pop()
method removes the element at a specified index and returns it.
li = [10, 20, 30, 40, 50]
index = 2
li.pop(index)
print(li)
Output
[10, 20, 40, 50]
Explanation:
pop()
method removes the element at the specified index (2
in this case), which is30
, from the listli
.- After the
pop()
, the listli
is updated to[10, 20, 40, 50]
, with the element at index2
removed.
Using List Slicing
We can use list slicing to remove an element by excluding the element at the given index.
li = [10, 20, 30, 40, 50]
index = 2
li = li[:index] + li[index+1:]
print(li)
Output
[10, 20, 40, 50]
Explanation:
- This code creates a new list by concatenating two slices of the original list
l
: one from the beginning up toindex
(excluding the element atindex
), and the other fromindex+1
to the end of the list. - As a result, the element at index
2
(which is30
) is removed, and the updated list is[10, 20, 40, 50]
.
Using del
Keyword
del keyword can be used to delete an element at a specific index.
li = [10, 20, 30, 40, 50]
index = 2
del li[index]
print(li)
Output
[10, 20, 40, 50]
Explanation:
- del statement removes the element at the specified index (2 in this case), which is 30, from the list li.
- After using del, the list li is updated to [10, 20, 40, 50], with the element at index 2 removed.
Using List Comprehension
List comprehension can be used to create a new list excluding the element at the specified index.
l = [10, 20, 30, 40, 50]
index = 2
l = [l[i] for i in range(len(l)) if i != index]
print(l)
Output
[10, 20, 40, 50]
Explanation:
- This code uses list comprehension to create a new list by iterating over the indices of the original list li and including only those elements where the index is not equal to 2.
- As a result, the element at index 2 (which is 30) is excluded, and the updated list is [10, 20, 40, 50].