Borislav Hadzhiev
Last updated: Jun 30, 2022
Check out my new book
To find the index of a tuple in a list:
enumerate
function to get an iterable with the indices and tuples.list_of_tuples = [(5, 'Alice'), (10, 'Bob'), (15, 'Carl'), (20, 'Dean')] # 👇️ [(0, (5, 'Alice')), (1, (10, 'Bob')), (2, (15, 'Carl')), (3, (20, 'Dean'))] print(list(enumerate(list_of_tuples))) # ✅ get list of all indices of tuples that match the condition result = [ idx for idx, tup in enumerate(list_of_tuples) if tup[1] == 'Carl' ] print(result) # 👉️ [2] print(list_of_tuples[result[0]]) # 👉️ (15, 'Carl') # -------------------------------------------------- # ✅ get the index of the first tuple that matches the condition result_1 = [tup[1] for tup in list_of_tuples].index('Carl') print(result_1) # 👉️ 2
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.
list_of_tuples = [(5, 'Alice'), (10, 'Bob'), (15, 'Carl'), (20, 'Dean')] # 👇️ [(0, (5, 'Alice')), (1, (10, 'Bob')), (2, (15, 'Carl')), (3, (20, 'Dean'))] print(list(enumerate(list_of_tuples)))
We used a list comprehension to iterate over the iterable.
list_of_tuples = [(5, 'Alice'), (10, 'Bob'), (15, 'Carl'), (20, 'Dean')] # 👇️ [(0, (5, 'Alice')), (1, (10, 'Bob')), (2, (15, 'Carl')), (3, (20, 'Dean'))] print(list(enumerate(list_of_tuples))) # ✅ get list of all indices of tuples that match the condition result = [ idx for idx, tup in enumerate(list_of_tuples) if tup[1] == 'Carl' ] print(result) # 👉️ [2] print(list_of_tuples[result[0]]) # 👉️ (15, 'Carl')
On each iteration, we check if the tuple element at index 1
is equal to the
string Carl
.
If the condition is met, we return the corresponding index.
If you need to only get the first tuple index for which the condition is met,
use a list comprehension and the index()
method.
To find the index of a tuple in a list:
list.index()
method to get the index of the first tuple with the
specified value.list_of_tuples = [(5, 'Alice'), (10, 'Bob'), (15, 'Carl'), (20, 'Dean')] result_1 = [tup[1] for tup in list_of_tuples].index('Carl') print(result_1) # 👉️ 2
The first step is to use a list comprehension to get a list of primitives from a list of tuples.
list_of_tuples = [(5, 'Alice'), (10, 'Bob'), (15, 'Carl'), (20, 'Dean')] # 👇️ ['Alice', 'Bob', 'Carl', 'Dean'] print([tup[1] for tup in list_of_tuples])
On each iteration, we return the tuple element at index 1
.
The last step is to use the list.index()
method to get the index of the value
in the list.
The list.index()
method returns the index of the first item whose value is
equal to the provided argument.
my_list = ['apple', 'banana', 'kiwi'] result = my_list.index('banana') print(result) # 👉️ 1
The method raises a ValueError
if there is no such item in the list.
Use this approach if you only need the index of the first tuple in the list for which the condition is satisfied.