Borislav Hadzhiev
Last updated: Jun 30, 2022
Photo from Unsplash
To find tuples in a list of tuples:
list_of_tuples = [('a', 1), ('b', 2), ('a', 3), ('c', 3)] # 👇️ check if the first element in a tuple is equal to specific value result_1 = [tup for tup in list_of_tuples if tup[0] == 'a'] print(result_1) # 👉️ [('a', 1), ('a', 3)] # 👇️ check if each tuple contains a value result_2 = [tup for tup in list_of_tuples if 'a' in tup] print(result_2) # 👉️ [('a', 1), ('a', 3)]
We used a list comprehension to find tuples in a list of tuples.
On each iteration, we check if the tuple element at index 0
has a value of a
and return the result.
list_of_tuples = [('a', 1), ('b', 2), ('a', 3), ('c', 3)] result_1 = [tup for tup in list_of_tuples if tup[0] == 'a'] print(result_1) # 👉️ [('a', 1), ('a', 3)]
The new list only contains the tuples for which the condition was satisfied.
To find tuples in a list that contain a certain value:
in
operator to check if each tuple contains the value.list_of_tuples = [('a', 1), ('b', 2), ('a', 3), ('c', 3)] result_2 = [tup for tup in list_of_tuples if 'a' in tup] print(result_2) # 👉️ [('a', 1), ('a', 3)]
On each iteration we check if the string a
is contained in the current tuple
and return the result.
The
in operator
tests for membership. For example, x in t
evaluates to True
if x
is a
member of t
, otherwise it evaluates to False
.
x not in t
returns the negation of x in t
.
Alternatively, you can use the filter()
function.
To find tuples in a list of tuples:
filter()
function to filter the list of tuples.filter
function returns an iterator containing the results.filter
object to the list()
class to convert it to a list.list_of_tuples = [('a', 1), ('b', 2), ('a', 3), ('c', 3)] result = list( filter( lambda tup: tup[0] == 'a', list_of_tuples ) ) # 👇️ [('a', 1), ('a', 3)] print(result)
The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.
filter
function returns a filter
object, so we had to pass the filter
object to the list()
class to convert it to a list.The lambda
function gets called with each tuple in the list, checks if the
first item in the tuple is equal to the string a
and returns the result.
The new list only contains the tuples for which the condition was met.