RubenGeert
RubenGeert

Reputation: 2952

Python: get item from list in list

How can I get an item from a list if that list is in a list? So if I have

mylist=[[range(4*(x-1)+1,4*(x-1)+5)]for x in range(1,5)]

then how can I retrieve the '1' from it? I always thought it was like

print mylist[0][0]

but it doesn't work.

Upvotes: 0

Views: 2786

Answers (2)

GSP
GSP

Reputation: 1076

Hate to be the Captain Obvious, but all you needed to do is just go 1 level deeper :)

>>> mylist=[[range(4*(x-1)+1,4*(x-1)+5)]for x in range(1,5)]
>>> mylist
[[[1, 2, 3, 4]], [[5, 6, 7, 8]], [[9, 10, 11, 12]], [[13, 14, 15, 16]]]
>>> mylist[0][0][0]
1

Upvotes: 0

Amber
Amber

Reputation: 526533

That's actually a triple-nested list, because range() returns a list, and then you have it wrapped in [].

Perhaps what you really wanted was...

mylist=[range(4*(x-1)+1,4*(x-1)+5) for x in range(1,5)]

At which point mylist[0][0] should do what you expect.

Upvotes: 7

Related Questions