How to Check if Value Exists in a 2D List (List of Lists) in Python
When working with nested data structures in Python, such as a two-dimensional list (a list containing other lists), you often need to determine if a specific value is present within any of the inner lists.
This guide demonstrates efficient and Pythonic ways to check for the existence of a value within a list of lists using the any()
function and standard loops.
Understanding the Problem: Searching Nested Lists
A two-dimensional list in Python is typically represented as a list where each element is itself another list. For example: [[1, 2], [3, 4], [5, 6]]
. Our goal is to efficiently check if a given value (e.g., 4
) exists as an element within any of these inner lists ([1, 2]
, [3, 4]
, or [5, 6]
).
Method 1: Using any()
with Generator Expression (Recommended)
This approach leverages the built-in any()
function combined with a generator expression and the in
operator for a concise and efficient check.
The Core Logic
- Generator Expression:
(value_to_find in sub_list for sub_list in list_of_lists)
iterates through eachsub_list
in the mainlist_of_lists
. For eachsub_list
, it performs a membership check (value_to_find in sub_list
), yieldingTrue
if the value is found in that specific sublist, andFalse
otherwise. any(iterable)
: Takes the sequence ofTrue
/False
values generated. It returnsTrue
as soon as it encounters the firstTrue
value (meaning the value was found in at least one sublist). If it goes through all sublists without finding the value (all checks yieldFalse
), it returnsFalse
. This short-circuiting makes it efficient.
Example Implementation
# Example Data
list_of_lists = [
['apple', 'banana'],
['orange', 'grape', 'kiwi'],
['melon', 'peach']
]
value_to_find = 'kiwi'
value_not_present = 'strawberry'
# Check if 'kiwi' exists in any sublist
found_kiwi = any(value_to_find in sub_list for sub_list in list_of_lists)
print(f"Searching for '{value_to_find}' in {list_of_lists}")
print(f"Found? {found_kiwi}") # Output: Found? True
if found_kiwi:
print(f"'{value_to_find}' is present in the 2D list.") # This is printed
else:
print(f"'{value_to_find}' is NOT present.")
# Check if 'strawberry' exists in any sublist
found_strawberry = any(value_not_present in sub_list for sub_list in list_of_lists)
print(f"\nSearching for '{value_not_present}' in {list_of_lists}")
print(f"Found? {found_strawberry}") # Output: Found? False
if found_strawberry:
print(f"'{value_not_present}' is present.")
else:
print(f"'{value_not_present}' is NOT present in the 2D list.") # This is printed
Output:
Searching for 'kiwi' in [['apple', 'banana'], ['orange', 'grape', 'kiwi'], ['melon', 'peach']]
Found? True
'kiwi' is present in the 2D list.
Searching for 'strawberry' in [['apple', 'banana'], ['orange', 'grape', 'kiwi'], ['melon', 'peach']]
Found? False
'strawberry' is NOT present in the 2D list.
Creating a Reusable Function
Encapsulating this logic in a function makes it easily reusable.
def is_value_in_2d_list(two_d_list, value):
"""Checks if a value exists in any sublist of a 2D list using any()."""
return any(value in sub_list for sub_list in two_d_list)
# Example Usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f"\nIs 5 in {matrix}? {is_value_in_2d_list(matrix, 5)}") # Output: True
print(f"Is 10 in {matrix}? {is_value_in_2d_list(matrix, 10)}") # Output: False
Finding the Sublist Containing the Value (Assignment Expression)
If you need to know which sublist contained the value (specifically, the first one found), you can use an assignment expression (:=
, the "walrus operator," Python 3.8+).
list_of_lists = [
['apple', 'banana'],
['orange', 'grape', 'kiwi'], # 'kiwi' is here
['melon', 'peach', 'kiwi'] # 'kiwi' is also here
]
value_to_find = 'kiwi'
found_sublist = None # Initialize
# Use assignment expression (match := sub_list) inside any()
if any(value_to_find in (match := sub_list) for sub_list in list_of_lists):
print(f"\n'{value_to_find}' was found!")
# 'match' will hold the *first* sublist where the condition was True
found_sublist = match
print(f"It was first found in the sublist: {found_sublist}")
# Output: It was first found in the sublist: ['orange', 'grape', 'kiwi']
# You can find its index within that sublist if needed
try:
index_in_sublist = found_sublist.index(value_to_find)
print(f"Index within that sublist: {index_in_sublist}") # Output: 2
except ValueError:
pass # Should not happen if 'in' check passed
else:
print(f"'{value_to_find}' was not found in any sublist.")
print(f"Final value of found_sublist: {found_sublist}")
# Output: Final value of found_sublist: ['orange', 'grape', 'kiwi']
Output:
'kiwi' was found!
It was first found in the sublist: ['orange', 'grape', 'kiwi']
Index within that sublist: 2
Final value of found_sublist: ['orange', 'grape', 'kiwi']
Due to any()
's short-circuiting, match
will only contain the first sublist where value_to_find
was present.
Method 2: Using a for
Loop
A standard for
loop provides a more explicit way to perform the check.
The Core Logic
Iterate through each sublist in the main list. Inside the loop, use the in
operator to check if the target value is present in the current sublist. If found, set a flag variable to True
and immediately exit the loop using break
, as we only need to know if it exists anywhere.
Example Implementation
list_of_lists = [
[10, 20],
[30, 40, 50],
[60, 70]
]
value_to_find = 50
value_not_present = 99
# Check for value_to_find
found_it_loop = False # Initialize flag
containing_sublist = None
print(f"\nSearching for {value_to_find} using a loop...")
for sub_list in list_of_lists:
print(f"Checking sublist: {sub_list}")
if value_to_find in sub_list:
print(f"--> Found {value_to_find}!")
found_it_loop = True
containing_sublist = sub_list # Store the sublist
break # Exit the loop, we found what we needed
if found_it_loop:
print(f"Result: {value_to_find} exists in the 2D list (found in {containing_sublist}).")
else:
print(f"Result: {value_to_find} does NOT exist in the 2D list.")
# Check for value_not_present
found_it_loop_2 = False
print(f"\nSearching for {value_not_present} using a loop...")
for sub_list in list_of_lists:
print(f"Checking sublist: {sub_list}")
if value_not_present in sub_list:
found_it_loop_2 = True
break
if found_it_loop_2:
print(f"Result: {value_not_present} exists in the 2D list.")
else:
print(f"Result: {value_not_present} does NOT exist in the 2D list.")
Output:
Searching for 50 using a loop...
Checking sublist: [10, 20]
Checking sublist: [30, 40, 50]
--> Found 50!
Result: 50 exists in the 2D list (found in [30, 40, 50]).
Searching for 99 using a loop...
Checking sublist: [10, 20]
Checking sublist: [30, 40, 50]
Checking sublist: [60, 70]
Result: 99 does NOT exist in the 2D list.
Choosing the Right Method
any()
with Generator Expression: Recommended for most cases. It's concise, efficient (due to short-circuiting), and considered more Pythonic for simple existence checks.for
Loop: More explicit and potentially easier for beginners to understand. Better suited if you need to perform additional actions inside the loop when a match is found or if the logic for checking within the sublist is more complex than a simplein
check.
Conclusion
Checking for a value within a two-dimensional list (list of lists) in Python is straightforward.
- The most idiomatic and often most efficient way is using
any(value in sub_list for sub_list in list_of_lists)
. - A standard
for
loop iterating through the outer list and using thein
operator on each inner list provides an explicit alternative.
Choose the method that best suits your code's readability needs and complexity requirements. Remember that any()
stops as soon as the first match is found.