Python Nested lists and iteration

python, python-2.7

Solution

[n for n, (i, s) in enumerate(t) if s == 'str_3']

Explanation:

>>> t = [[100, 'str_1'], [200, 'str_2'], [300, 'str_3']]

# Use enumerate to get each list item along with its index.
>>> list(enumerate(t))
[(0, [100, 'str_1']), (1, [200, 'str_2']), (2, [300, 'str_3'])]

# Use list comprehension syntax to iterate over the enumeration.
>>> [n for n, (i, s) in enumerate(t)]
[0, 1, 2]

# An if condition can be added right inside the list comprehension.
>>> [n for n, (i, s) in enumerate(t) if s == 'str_3']
[2]
>>> [n for n, (i, s) in enumerate(t) if s == 'str_1234']
[]

This will return all of the matching indices, since there could be more than one.

If you know there will only be one index, may I suggest using a dict instead of a nested list? With a dict you can lookup elements in constant time using very straightforward syntax, rather than having to iterate.

>>> t = {'str_1': 100, 'str_2': 200, 'str_3': 300}

>>> 'str_3' in t
True
>>> t['str_3']
300

>>> 'str_1234' in t
False
>>> t['str_1234']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'str_1234'

Problem

I am new to Python and I did my search but I could not find what I am looking for. I apologise in advance if this question has been asked and if I could not find it due to my lack of not knowing the name of what I am trying to achieve. I will gladly read any document you might suggest. I have a list of lists. e.g. => [int, 'str'] ``` t = [[0234, 'str_0'], [1267, 'str_1'], [2445, 'str_2']] ``` I want to find out if `a str` exists in index(1) position of one of the lists of list t. I can do this with a function containing 2 for or while loops but what I am seeking is to achieve this, if possible, using one single iteration. I want to learn the shortest function. `for input str('str_3'), I want to get int(2)` (index of the list which has str_3 on its own 1st index location) for str_1, I want to get int(0) and for str_1234 I want to get False as it is not in any of the lists within the `list t` As a newbie, I would normally do: ``` for n in range(len(t)): if t[n][1] == 'str_1' return n return False ``` What I am seeking to get is, if possible, a better and shorter way of achieving this in one line of a code or just simply to learn if there is a smarter, better or more pythonic way that any one of you who is surely more experienced would recommend. Thank you

Original source