Robert Berman wrote:
Hi,

Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'.

You will need to explain what you mean by "the index of 'c'".

Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]?

Or do you mean 2, because 'c' is in the sub-list at position 2?

What happens if there is a sub-list ['d', 'c']? Should that also count? What about sub-sub-lists, should they be checked too?

Here is a version which checks each sub-list in turn, and returns the index of any 'c' it finds of the first such sub-list.

def inner_find(list_of_lists):
    for sublist in list_of_lists:
        try:
            return sublist.index('c')
        except ValueError:
            pass  # go to the next one
    # If not found at all:
    raise ValueError('not found')


Here's a version which finds the index of the first sub-list that begins with 'c' as the zeroth element:

def match_sublist(list_of_lists):
    for i, sublist in enumerate(list_of_lists):
        if sublist and sublist[0] == 'c':
            return i
    raise ValueError('not found')




Other variations on these two techniques are left for you to experiment with.



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to