Python check if all elements in list are in another list

Python check if list contains elements of another list

In this post, you will learn how to check if a list contains elements of another list using the Python programming language.

A list is a sequence of indexed and ordered values, like an array. It is mutable, which means we can change the order of elements in a list. It contains a list of any type of data object with a comma separated and enclosed within a square bracket. In the development process, we may come to a situation in which we need to check if a list contains elements of another list. Here, we have mentioned different ways to achieve this task.

Check if list contains elements of another list using any() function

The any() function is an inbuilt function in Python which returns true if any of the elements of a given iterable are True, else it returns False. In the given example, we have taken two variables, list_x and list_y, and checked if a list contains any item from another list.

## checking any element of list_x in list_y list_x = [11, 31, 12, 51] list_y = [51, 12, 31] check = any(item in list_x for item in list_y) print(check)

Check if list contains elements of another list using all() function

The all() function of Python returns True if all elements in the given iterable are true. If not, it returns False. In the given example, we have taken two variables, list_x and list_y, and checked if all elements exist in another list. If satisfied, it returns True else it returns False.

## checking any elment of list_x in list_y list_x = [10, 12, 32, 25] list_y = [10, 32, 25] check = all(item in list_x for item in list_y) print(check)

Check if list contains elements of another list using intersection method

In the given example, we have used the Python set intersection() method to find if there is any match between the two given list elements.

## checking any elment of list_x in list_y list_x = [1, 2, 3, 4] list_y = [2, 3] set_x = set(list_x) set_y = set(list_y) print(set_x.intersection(set_y))

Источник

Читайте также:  1с http сервис html

Python : Check if a list contains all the elements of another list

In this article we will discuss if a list contains all or any elements of another list.

Suppose we have have two list i.e.

# List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # List of string list2 = ['there' , 'hello', 'Hi']

Check if list1 contains all elements of list2 using all()

''' check if list1 contains all elements in list2 ''' result = all(elem in list1 for elem in list2) if result: print("Yes, list1 contains all elements in list2") else : print("No, list1 does not contains all elements in list2"

Python all() function checks if all Elements of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if element exists in list1.

Check if list1 contains any elements of list2 using any()

''' check if list1 contains any elements of list2 ''' result = any(elem in list1 for elem in list2) if result: print("Yes, list1 contains any elements of list2") else : print("No, list1 contains any elements of list2")

Python any() function checks if any Element of given Iterable is True. So, convert the list2 to Iterable and for each element in Iterable i.e. list2 check if any element exists in list1.

Frequently Asked:

Complete example is as follows,

def main(): # List of string list1 = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # List of string list2 = ['there' , 'hello', 'Hi'] ''' check if list1 contains all elements in list2 ''' result = all(elem in list1 for elem in list2) if result: print("Yes, list1 contains all elements in list2") else : print("No, list1 does not contains all elements in list2") ''' check if list1 contains any elements of list2 ''' result = any(elem in list1 for elem in list2) if result: print("Yes, list1 contains any elements of list2") else : print("No, list1 contains any elements of list2") if __name__ == '__main__': main()
Yes, list1 contains all elements in list2 Yes, list1 contains any elements of list2

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Check if Python List Contains All Elements of Another List

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

To understand this demo program, you should have basic Python programming knowledge.

Check if Python List Contains Elements of Another List

In the sample below, 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. There could be multiple ways to achieve it.

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']

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 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 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

Источник

Python – Check List Contains All Elements Of Another List

In this tutorial, we will look at how to check if a list contains all the elements of another list in Python with the help of some examples.

How to check if a list contains all elements of another list?

check if one list contains all elements of another list

In Python, you can use a combination of the built-in all() function, list comprehension, and the membership operator to check if a list contains all elements of another list.

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Use the following steps to check if all elements in the list ls1 are present in the list ls2 –

  • In a list comprehension, for each element in the list ls1 , check if it present in the list ls2 using the membership operator, in .
  • Apply the Python built-in all() function to return True only if all the items in the above list comprehension correspond to True .

You can use the following syntax to implement the above steps (check if all elements in ls1 are present in ls2 ).

all([item in ls2 for item in ls1])

It returns True only if all the in ls1 are present in ls2 .

Let’s now look at some examples –

# create two lists ls1 = [1, 2, 3] ls2 = [1, 2, 3, 4, 5] # check if ls2 contains all elements from ls1 print(all([item in ls2 for item in ls1]))

We get True as the output since all the elements in the list ls1 are present in the list ls2 .

Let’s now look at another example.

# create two lists ls1 = [1, 2, 6] ls2 = [1, 2, 3, 4, 5] # check if ls2 contains all elements from ls1 print(all([item in ls2 for item in ls1]))

Here we get False as the output because not all elements in the list ls1 are present in the list ls2 . The element 6 is not present in ls2 .

Using set issubset() function

Alternatively, you can convert the two lists to sets and use the set issubset() function to check if all elements in one list are present in another list or not.

# create two lists ls1 = [1, 2, 3] ls2 = [1, 2, 3, 4, 5] # check if ls2 contains all elements from ls1 s1 = set(ls1) s2 = set(ls2) print(s1.issubset(s2))

We get the same result as above. Here, we convert the lists ls1 and ls2 to sets s1 and s2 respectively. And then check if the set s1 is a subset of the set s2 . This gives us whether all elements in ls1 are present in ls2 or not.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью