How do you check if there is a list within a list in Python?

Python | Check if a list exists in given list of lists

Given a list of lists, the task is to check if a list exists in given list of lists.

Input : lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] list_search = [4, 5, 6] Output: True Input : lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]] list_search = [4, 12, 54] Output: False

Let’s discuss certain ways in which this task is performed.

Method #1: Using Counter
The most concise and readable way to find whether a list exists in list of lists is using Counter.




# Python code find whether a list
# exists in list of list.
import collections
# Input List Initialization
Input = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
# List to be searched
list_search = [2, 3, 4]
# Flag initialization
flag = 0
# Using Counter
for elem in Input:
if collections.Counter[elem] == collections.Counter[list_search] :
flag = 1
# Check whether list exists or not.
if flag == 0:
print["False"]
else:
print["True"]
Output: True


Method #2: Using in






# Python code find whether a list
# exists in list of list.
# Input List Initialization
Input = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
# List to be searched
list_search = [1, 1, 1, 2]
# Using in to find whether
# list exists or not
if list_search in Input:
print["True"]
else:
print["False"]
Output: True


Method #3: Using any




# Python code find whether a list
# exists in list of list.
# Input List Initialization
Input = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]]
# List to be searched
list_search = [4, 5, 6]
# Using any to find whether
# list exists or not
if any[list == list_search for list in Input]:
print["True"]
else:
print["False"]
Output: True




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

Python | Check if element exists in list of lists

Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task.

Method #1: Using any[]

any[] method return true whenever a particular element is present in a given iterator.




# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = any[elem_to_find in sublist for sublist in ini_list]
res2 = any[elem_to_find1 in sublist for sublist in ini_list]
# printing result
print[str[res1], "\n", str[res2]]
Output: True False


Method #2: Using operator in

The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.






# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem = 8
elem1 = 0
# element exists in listof listor not?
res1 = elem in [item for sublist in ini_list for item in sublist]
res2 = elem1 in [item for sublist in ini_list for item in sublist]
# printing result
print[str[res1], "\n", str[res2]]
Output: True False


Method #3: Using itertools.chain[]

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.




# Python code to demonstrate
# finding whether element
# exists in listof list
from itertools import chain
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = elem_to_find in chain[*ini_list]
res2 = elem_to_find1 in chain[*ini_list]
# printing result
print[str[res1], "\n", str[res2]]
Output: True False




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

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 element exists in list using python “in” Operator

Condition to check if element is in List :

elem in LIST
It will return True, if element exists in list else return false.

For example check if ‘at’ exists in list i.e.

''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print["Yes, 'at' found in List : " , listOfStrings]
Condition to check if element is not in List :
''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print["Yes, 'time' NOT found in List : " , listOfStrings]
Advertisements

Method 1: Using isinstance[] With any[]

The easiest solution to our problem is to use the isinstance[] method and a generator expression within the any[] function. Before diving into the solution, let us understand the usage of the isinstance[] and any[] methods that will help us to check the list if it is nested or not.

isinstanceis a built-in method in Python which returnsTruewhen the specified object is an instance of the specified type, otherwise it returnsFalse.

Syntax:

Example:

a = isinstance[25, int] print[a]

Output:

True

◉any[] is a built-in function that returns True if any element in an iterable is True, otherwise it returns False.

Syntax:

any[iterable]

Example:

li = [0, 10, 100, 1000] x = any[li] # Returns True because the first item is True print[x]

Output:

True

Now that we know the usage of each function, let us have a look at the solution to our problem. Please follow the code given below that demonstrates the solution.

Solution

li_1 = [1, 2, 3] # flat list li_2 = [[1, 2, 3], [4, 5, 6]] # nested list # Testing for nested list li_1_output = any[isinstance[i, list] for i in li_1] li_2_output = any[isinstance[i, list] for i in li_2] # Printing output print["Is li_1 Nested?", li_1_output] print["IS li_2 Nested?", li_2_output]

Output:

Is li_1 Nested? False IS li_2 Nested? True

Explanation

In the above code theany[] method allows us to check for each occurrence of the list while the isinstance[] method checks if each instance of an element inside the list is a list itself or not. Therefore in the first case, the output is False since Python does not find any occurrence of another list within li_1 while in the second case it finds a couple of lists within the parent list li_2 and it returns True.

Check if a Python List Contains an Item Using in

One of the easiest and most Pythonic ways to check for membership in a Python list is to use the in key. Technically, the in keyword serves two purposes:

  1. To check for membership in a list, and
  2. To loop over a items in a for loop

In this case, we’ll use the in keyword to check if an item exists in a list. This provides a readable and almost plain-English way to check for membership. Let’s see what this looks like:

# Check if a Python List Contains an Item items = ['datagy', 'apples', 'bananas'] if 'datagy' in items: print['Item exists!'] # Returns: Item exists

We can that by writing if 'item' in items, we’re able to evaluate if something exists in our list. This is a really intuitive way to check if items exist or not.

In the next section, you’ll learn how to use Python to check if an item doesn’t exist.

Need to replace an item in a list? Check out my tutorial on this topic here: Python: Replace Item in List [6 Different Ways]

Check if a Python List Doesn’t Contain an Item Using not in

In this section, you’ll learn to check if a list doesn’t contain an item. We can do this by negating the in keyword, using the not keyword. Similar to the example above, this reads like relatively plain English. Let’s see how we can use the not in keyword to see if an item isn’t a list:

# Check if a Python List Doesn't Contain an Item items = ['datagy', 'apples', 'bananas'] if 'oranges' not in items: print["Item doesn't exists!"] # Returns: Item doesn't exist!

We can see that the not in keyword allows us to determine if an item doesn’t exist. It returns the opposite truthiness of the in keyword. Because of this, it allows us to write cleaner code.

In the next section, you’ll learn to check for membership in a Python list using the .count[] method.

Need to remove an item for a list? Check out my tutorial to learn how to here: Remove an Item from a Python List [pop, remove, del, clear]

Video liên quan

Bài mới nhất

Chủ Đề