1

I am just learning Python and I need some advice regarding searching items in a list. I have a list that contains a list of lists. How can I search for an item in a list and return the value from the same list like the example below.

Example: 
myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

word = 'Green'
return Pear

Is is possible to find the first instance or the n-th instance in the list as well?

first_instance = 'Red'
return Tomato

last_instance = 'Red'
return Strawberry
1
  • will there be two elements in the sub_lists always? or is there a possibility of there being more than two elements? Commented May 6, 2013 at 8:54

5 Answers 5

3

You can fetch all such elements:

instances = [x[1] for x in myList if x[0] == 'Red']

And process instances[0], instances[-1], etc.

To get the first one only, I'd go with @eumoro's approach using a generator expression.

Sign up to request clarification or add additional context in comments.

Comments

2
myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

# first_instance_red
next(elem[1] for elem in myList if elem[0] == 'Red')

# last_instance_red
next(elem[1] for elem in myList[::-1] if elem[0] == 'Red')

1 Comment

Although OP's use case is tiny, so it won't matter, I would rather use reversed to avoid the shallow copy of [::-1] here since the instance may be found early.
1

You can use collections.defaultdict:

Using this once the dictionary is created it'll take only O(1) lookup to find any instance of "Red" or any other color.

>>> myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> dic['Red'][0] #first instance
'Tomato'
>>> dic['Red'][-1] #last instance
'Strawberry'
>>> dic["Yellow"][0] #first instance of Yellow
'Lemon'

Define a simple function here to handle Index errors:

>>> def solve(n, color, dic):
    try:
        return dic[color][n]
    except IndexError:
        return "Error: {0} has only {1} instances".format(color,len(dic[color]))
...     
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> solve(0, "Red", dic)
'Tomato'
>>> solve(-1, "Red", dic)
'Strawberry'
>>> solve(0, "Yellow", dic)
'Lemon'
>>> solve(1, "Yellow", dic)
'Error: Yellow has only 1 instances'

Comments

0

OK. All of the other answers are probably more pythonic than this. I'm just adding it, because I think when starting out, having some simple loops helps.

def find_first(key, list_of_pairs):
    for pair in list_of_pairs:
        if pair[0] == key:
            return pair[1]
    return None # hey, maybe it isn't in the list at all!

Oh, and you could define find_last as:

find_last = lambda k, lop: find_first(key, reversed(lop))

So. In python you can always go this route. Except you should really look into the list comprehensions mentioned by the other answers.

Comments

0

Use a dict comprehension, a one liner to make a dict out of a list. Then, query the dict.

>>> d={x[0]:x[1] for x in myList}

d equals {'Green': 'Pear', 'Yellow': 'Lemon', 'Red': 'Strawberry'}

>>> d['Green']
'Pear'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.