How to Check if an Item in a List is in Another List in Python?

Estimated read time 2 min read

To check if an item in a list is in another list in Python, you can use a simple conditional statement with the in operator. Here’s an example:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

for item in list1:
    if item in list2:
        print(f"{item} is in list2")
    else:
        print(f"{item} is not in list2")

In this example, we have two lists list1 and list2. We loop through each item in list1, and for each item, we check if it’s in list2 using the in operator. If it is, we print a message indicating that it’s in list2. If not, we print a message indicating that it’s not in list2.

Output:

1 is not in list2
2 is not in list2
3 is in list2
4 is in list2
5 is in list2

Alternatively, you can use a list comprehension to create a new list with only the items that are in both lists:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

common_items = [item for item in list1 if item in list2]
print(common_items)

Output:

[3, 4, 5]

In this example, we use a list comprehension to create a new list called common_items. We loop through each item in list1, and for each item, we check if it’s in list2 using the in operator. If it is, we add it to the new list. Finally, we print the new list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply