A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-check-two-lists-least-one-element-common/ below:

Python - Check if two lists have at-least one element common

Python - Check if two lists have at-least one element common

Last Updated : 10 Dec, 2024

Checking if two lists share at least one common element is a frequent task when working with datasets, filtering, or validating data. Python offers multiple efficient ways to solve this depending on the size and structure of the lists.

Using set Intersection

Converting both lists into sets and finding their intersection is the most efficient way to check for common elements especially for large lists.

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

# Find common elements using set intersection
common = set(a) & set(b)

# Check if there are common elements
if common:
    print("Common", common)
else:
    print("Not common.")
Explanation:

Let's explore some other methods on how to check if two lists have at least one element in common

Using any()

The any() function efficiently checks for at least one match between two lists. This approach avoids creating sets and works well for small to medium-sized lists.

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

# Check for at least one common element
if any(item in b for item in a):
    print("Common elements exist.")
else:
    print("No common elements.")

Output
Common elements exist.
Explanation: Using Loops

A simple nested loop can also check for common elements. The loop breaks early if a common element is found.

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

# Check for common elements using nested loops
common = False
for i in a:
    if i in b:
        common = True
        break

if common:
    print("Common elements exist.")
else:
    print("No common elements.")

Output
Common elements exist.
Explanation: Using filter() and set()

Combining filter() with set() provides another clean way to find common elements. It’s efficient for functional programming scenarios. The result is converted to a set to remove duplicates.

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

# Find common elements using filter and set
common = set(filter(lambda x: x in b, a))

if common:
    print("Common", common)
else:
    print("No common elements.")
Explanation: Using List Comprehension

List comprehension can collect all the common elements but it is less efficient compared to set operations when lists are large.

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

# Find common elements using list comprehension
common = [item for item in a if item in b]

if common:
    print("Common", common)
else:
    print("No common elements.")
Explanation:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4