Home > Backend Development > Python Tutorial > How Can I Find Common Elements Between Two Lists in Python?

How Can I Find Common Elements Between Two Lists in Python?

Mary-Kate Olsen
Release: 2024-12-04 00:16:09
Original
814 people have browsed it

How Can I Find Common Elements Between Two Lists in Python?

Comparing Lists in Python for Matching Elements

In Python, comparing two lists to find the common elements can be achieved using various approaches. Let's explore them:

Method 1: Using Set Intersection

This method converts the lists to sets, which are unordered collections of unique elements. Intersecting these sets using the & operator provides the values that appear in both lists.

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

result = set(a) & set(b)
# result: {5}
Copy after login

Method 2: Using List Comprehension

This method iterates over pairs of elements from both lists using the zip function. It creates a new list containing only the elements that are equal in both lists.

result = [i for i, j in zip(a, b) if i == j]
# result: [5]
Copy after login

Method 3: Using Counter

The collections.Counter class can be used to count the occurrences of elements in both lists. The intersection method of the Counter object returns a new Counter object with the matching elements.

import collections
a_counter = collections.Counter(a)
b_counter = collections.Counter(b)

result = a_counter & b_counter
# result: Counter({5: 1})
Copy after login

The above is the detailed content of How Can I Find Common Elements Between Two Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template