Skip to content

Remove list from list Python | Example code

  • by

Using list comprehension or simple looping will be able to remove the list from the list and create a new one in Python.

The list comprehension can remove all occurrences by creating a new list with all elements except the specified list.

Example remove the list from the list in Python

In simple example code, where we have a and b lists, the new list should have items that are only in the list a.

Using a list comprehension that tells us quite literally which elements need to end up in new_list:

a = ['apple', 'carrot', 'lemon']
b = ['pineapple', 'apple', 'tomato']

new_list = [fruit for fruit in a if fruit not in b]

print(new_list)

Output:

Remove list from list Python

Another example

Using a for loop and append method.

a = ['apple', 'carrot', 'lemon']
b = ['pineapple', 'apple', 'tomato']

new_list = []
for fruit in a:
    if fruit not in b:
        new_list.append(fruit)

print(new_list)

Output: [‘carrot’, ‘lemon’]

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading