python

How to Remove More Than One Element From List in Python

In this tutorial, we are going to see how to remove more than one element from a list in Python. Python has a few methods of removing items from a list. Each of these is explained below with sample codes so you can understand how to use it and see the difference.
 

 

Remove More Than One Element From List Using Iterative approach

We will iterate through the list and remove each element divisible by 2:

# List of numbers
nbrs = [1, 2, 3, 4, 5, 6, 7, 8]

# Remove all numbers from the list that are divisible by 2
for elem in nbrs:
    if elem % 2 == 0:
        nbrs.remove(elem)
        
print(nbrs)

Output:

[1, 3, 5, 7]

 

Remove More Than One Element From List Using list comprehension

Same can be achieved by list comprehension

# List of numbers
nbrs = [1, 2, 3, 4, 5, 6, 7, 8]
# Remove all numbers from the list that are divisible by 2
nbrs = [ i for i in nbrs if i % 2 != 0]
# Print the new list
print(nbrs)

Output:

[1, 3, 5, 7]
 

Remove More Than One Element From List by Index Range Using “del”

Suppose we want to remove multiple items from a list by index range, then we can use the “del” keyword.

# List of numbers
nbrs = [1, 2, 3, 4, 5, 6, 7, 8]
# Removes elements from 1 to 4 (indexes)
del nbrs[1:5]
# Print the new list
print(nbrs)

Output:

[1, 6, 7, 8]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *