Kevin
Kevin

Reputation: 49

Return the index number/order of a value in a tuple

I have a list:

my_tuple = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'), ('blueberry', 'blue')]

I am trying to obtain the index number/order for a given value in the list.

Example

I want to get the index of 'lime' which would be 1. Or the index of 'blueberry' which is 4.

I tried to use:

my_tuple.index('apple') 
my_tuple.index('red') 

but my syntax is incorrect.

I was hoping to be able to obtain the index number from the input in either element. for example both index('apple') and index('red') would return 0.

Ex.)

>>>my_tuple.index('apple')
 0
>>>my_tuple.index('red')
 0

Is this possible? Or would I need to input both the first and second value in order to obtain the index number?

Upvotes: 0

Views: 207

Answers (4)

martineau
martineau

Reputation: 123443

Here's another way to do it using enumerate(). It creates a list of the indices of those elements that contained the value, and then returns the index of the first (and possibly only) one:

def value_index(values, value):
    try:
       return [i for i, group in enumerate(values) if value in group][0]
    except IndexError:
        pass
    raise ValueError(f'{value!r} not found')

my_tuple = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'),
            ('blueberry', 'blue')]

print(value_index(my_tuple, 'apple'))   # -> 0
print(value_index(my_tuple, 'yellow'))  # -> 2
print(value_index(my_tuple, 'purple'))  # -> ValueError: 'purple' not found

Upvotes: 1

zoldxk
zoldxk

Reputation: 1

How about:

my_tuple = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'), ('blueberry', 'blue')]
[x for x, y in enumerate(my_tuple) if 'blueberry' in y]

out:

[3]

Upvotes: 0

Buddy Bob
Buddy Bob

Reputation: 5889

I suggest you use enumerate and iterate through your list. If your wanted item is in a tuple, you return that index.

lst = [('apple', 'red'), ('lime', 'green'), ('banana', 'yellow'), ('blueberry', 'blue')]
def look(my_tuple,wanted):
    for count,food in enumerate(my_tuple):
        if wanted in food:
            return count
print(look(lst,'apple'))

output

0

Upvotes: 0

enzo
enzo

Reputation: 11486

You can do something like this:

def index_of(values, value):
    return next((i for i, tupl in enumerate(values) if value in tupl), -1)
    
print(index_of(my_tuple, 'apple'))   # 0
print(index_of(my_tuple, 'red'))     # 0
print(index_of(my_tuple, 'lime'))    # 1
print(index_of(my_tuple, 'banana'))  # 2
print(index_of(my_tuple, 'monkey'))  # -1

Upvotes: 4

Related Questions