I have created a list that looks something like this:
items = [["one","two","three"], 1, ["one","two","three"], 2]
How do I access e.g. '1' in this list?
I have created a list that looks something like this:
items = [["one","two","three"], 1, ["one","two","three"], 2]
How do I access e.g. '1' in this list?
item[1]
is the correct item. Remember that lists are zero-indexed.
If you wanted to get one
(The one in the first sublist), then you can do items[0][0]
Similiarly, for the second sublist, you can do items[2][0]
You can access it by index:
>>> items = [["one","two","three"], 1, ["one","two","three"], 2]
>>> items[1]
1
Or, if you want to find a position of an item in the list by value, use index()
method:
>>> items.index(1)
1
>>> items.index(2)
3
You can use list.index()
to get the index of the value:
>>> items = [["one","two","three"], 1, ["one","two","three"], 2]
>>> print items.index(1)
1
Then, to access it:
>>> print items[1]
1
However, list.index()
only returns the first instance. To get multiple indexes, use enumerate()
:
>>> [i for i, j in enumerate(items) if j == 1]
[1]
This loops through the whole list, giving a sort of count along with it. For example, printing i
and j
:
>>> for i, j in enumerate(items):
... print i, j
...
0 ['one', 'two', 'three']
1 1
2 ['one', 'two', 'three']
3 2
You can assume that i
is the index and j
is the value.