Sobes.tech
Junior — Middle

How can you find common elements between two lists in Python?

sobes.tech AI

Answer from AI

To find common elements between two lists in Python, you can use set intersection, as sets automatically remove duplicates and allow efficient intersection operations.

Example:

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

common_elements = list(set(list1) & set(list2))
print(common_elements)  # Outputs: [4, 5]

If order matters or you need to consider repetitions, you can use list comprehension:

common_elements = [x for x in list1 if x in list2]

However, this method is less efficient for large lists.