0

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?

Hayley van Waas
  • 429
  • 3
  • 12
  • 21
  • 3
    This doesn't truly address the question, but lists shouldn't contain heterogeneous data. http://stackoverflow.com/questions/626759/whats-the-difference-between-list-and-tuples-in-python Instead consider using a tuple for each "set": `items = [(["one", "two", "three"], 1), (["one", "two", "three"], 2)]` Then you can get the 1 via items[0][1]. – Steve Howard Sep 07 '13 at 00:12

3 Answers3

4

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]

2

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
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

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.

TerryA
  • 58,805
  • 11
  • 114
  • 143