Remove list from list Python | Example code

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

Example remove list from list Python

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 which 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’]

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.