TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python List Contains Elements of Another List
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Python List Contains Elements of Another List

Last updated: Apr 17, 2024 9:15 pm
By Meenakshi Agarwal
Share
11 Min Read
Check If Python List Contains Elements Of Another List
Check If Python List Contains Elements Of Another List
SHARE

In this short tutorial, you will learn to check if a Python list contains all the elements of another list and show the result using the print() function.

Contents
all() methodany() methodin keywordset() methodCollections class to check if a Python list contains another listList comprehension to check if a Python list contains another listComparing different methodsWhere can you apply these methods?Summary

We can solve this using different methods. Each technique is explained using a demo program. To understand them, make sure you have basic Python programming knowledge.

Check if a Python List Contains Elements of Another List

In each demo program, we are using two lists having overlapping values. One of these is the big one which holds all the elements of the second one.

  • List1 – This list contains all or some of the elements of another.
  • List2 – It is a subset of the first one.

Now, we’ve to programmatically prove that List1 contains the elements of List2. As stated earlier, there are multiple ways to achieve it. Let’s dive in to learn them.

all() method

To demonstrate that List1 has List2 elements, we’ll use the all() method.

# Program to check the list contains elements of another list

# List1
List1 = ['python' , 'javascript', 'csharp', 'go', 'c', 'c++']

# List2
List2 = ['csharp1' , 'go', 'python']

check = all(item in List1 for item in List2)

if check is True:
print("The list {} contains all elements of the list {}".format(List1, List2))
else :
print("No, List1 doesn't have all elements of the List2.")

The output of the above code is as follows:

The list ['python', 'javascript', 'csharp', 'go', 'c', 'c++'] contains all elements of the list ['csharp', 'go', 'python']

Also Read: Python Get the Last Element in a List

any() method

Another method is any() which we can use to check if the list contains any elements of another one.

# Program to check the list contains elements of another list

# List1
List1 = ['python' ,  'javascript', 'csharp', 'go', 'c', 'c++']
 
# List2
List2 = ['swift' , 'php', 'python']

check =  any(item in List1 for item in List2)
 
if check is True:
    print("The list {} contains some elements of the list {}".format(List1, List2))    
else :
    print("No, List1 doesn't have any elements of the List2.")

The output of the above code is as follows:

The list ['python', 'javascript', 'csharp', 'go', 'c', 'c++'] contains some elements of the list ['swift', 'php', 'python']

in keyword

The “in” keyword is a very efficient way to check if a Python list contains a particular element. However, it can become inefficient for larger lists.

In this method, we’ll write a custom search method to test if the first list contains the second one. While iterating the lists if we get an overlapping element, then the function returns true. The search continues until there is no element to match and returns false.

# Program to check if a Python list contains elements of another list
  
def list_contains(List1, List2): 
    check = False
  
    # Iterate in the 1st list 
    for m in List1: 
  
        # Iterate in the 2nd list 
        for n in List2: 
    
            # if there is a match
            if m == n: 
                check = True
                return check  
                  
    return check 
      
# Test Case 1
List1 = ['a', 'e', 'i', 'o', 'u'] 
List2 = ['x', 'y', 'z', 'l', 'm'] 
print("Test Case#1 ", list_contains(List1, List2)) 

# Test Case 2  
List1 = ['a', 'e', 'i', 'o', 'u']  
List2 = ['a', 'b', 'c', 'd', 'e']  
print("Test Case#2 ", list_contains(List1, List2)) 

The output of the above code is as follows:

Test Case#1  False
Test Case#2  True

set() method

We’ll use the set() method to convert the lists and call the Python set intersection() method to find if there is any match between the list elements.

# Program to check if a Python list contains elements of another list
  
def list_contains(List1, List2): 
  
    set1 = set(List1) 
    set2 = set(List2) 
    if set1.intersection(set2): 
        return True 
    else: 
        return False
      
# Test Case 1
List1 = ['a', 'e', 'i', 'o', 'u'] 
List2 = ['x', 'y', 'z', 'l', 'm'] 
print("Test Case#1 ", list_contains(List1, List2)) 

# Test Case 2  
List1 = ['a', 'e', 'i', 'o', 'u']  
List2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']  
print("Test Case#2 ", list_contains(List1, List2)) 

The output of the above code is as follows:

Test Case#1  False
Test Case#2  True

Collections class to check if a Python list contains another list

The collections.Counter() class creates a counter object from a list. A counter object is a dictionary that stores the count of each element in a list.

We can use the collections.Counter() class to check if a Python list contains all elements of another list by comparing the two counter objects. If the two counter objects are equal, then the first list contains all elements of the second list, and in the same quantity.

Here is an example of how to use the collections.Counter() class to check if a Python list contains all elements of another list:

from collections import Counter

def list_contains_elements_of_list(list1, list2):
    """Returns True if list1 contains all elements of list2, False otherwise."""
    
    counter1 = Counter(list1)
    counter2 = Counter(list2)
    
    # Check if counter2 is a subset of counter1
    return all(counter2[element] <= counter1[element] for element in counter2)

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

print(list_contains_elements_of_list(list1, list2))
print(list_contains_elements_of_list(list1, list3))

# True
# False

We introduced a third list in the above code to showcase a failure case. It means the case when the list1 doesn’t contain all the elements of another list.

Must Read: Python Remove Last Element from a List

List comprehension to check if a Python list contains another list

A list comprehension in Python is a way to create a new list from an existing list. List comprehensions are concise and efficient, and they can be used to perform a variety of tasks, including checking if a list contains all elements of another list.

Here is an example of how to use list comprehension to check if a Python list contains all elements of another list:

def list_contains_elements_of_list(list1, list2):
  """Returns True if list1 contains all elements of list2, False otherwise."""

  return all(element in list1 for element in list2)


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

print(list_contains_elements_of_list(list1, list2))
print(list_contains_elements_of_list(list1, list3))

# True
# False

Comparing different methods

To help you decide which method to use for your application, we have benchmarked the different methods on a list of 10,000 elements. The following table shows the results of the benchmarking:

MethodTime taken (in seconds)
in keyword0.002
all() function0.001
set() constructor0.003
collections.Counter() class0.002
List comprehension0.001
Comparing Methods to Check If the List Contains Elements of Another List

As you can see, the all() function and list comprehension are the most efficient methods for checking if a Python list contains all elements of another list.

However, you may consider the following points for checking if a Python list contains all elements of another list.

  • The size of the lists: If the lists are small, then the in keyword will be the most efficient method. However, if the lists are large, then the all() function or the list comprehension will be more efficient.
  • The presence of duplicate elements: If the lists contain duplicate elements, then the collections.Counter() class is the most efficient method.
  • The frequency of the check: If you need to perform this check frequently, then the all() function or the list comprehension are good options to consider.

Where can you apply these methods?

Here are a few scenarios where you can use the above methods to check if a Python list contains all elements of another list:

  • Validate user input: You might need to check if a list of user input contains all of the required elements. For example, in a web app, you may need to check if a user has entered all of the required fields in a form.
  • Check for duplicate elements: You can apply the methods to check if the lists contain any duplicate elements. For example, in an email manager, you may have to filter a list of email addresses containing duplicate emails.
  • Merging two lists: By using these methods, you can check if two lists are merged successfully or not. For example, a data science app may have a feature to merge two lists into a single list for analysis. It also then cross-checks whether the merge was successful or not.

Summary

In this tutorial, we have learned how to check if a Python list contains all elements of another list. We have explored different methods for doing this including any() and all() functions. These techniques provide essential tools for effective list comparisons. Feel free to use these in your Python programs to meet your specific use case. We’ll be happy to hear about your experience once you use them.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Generate Random Integer Numbers Python Program to Generate Random Integers
Next Article Python program to generate a Fibonacci sequence Generate Fibonacci Sequence in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x