Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lists python

Tags:

python

Can anyone tell me how can I call for indexes in a nested list?

Generally I just write:

for i in range (list)

but what if I have a list with nested lists as below:

Nlist = [[2,2,2],[3,3,3],[4,4,4]...]

and I want to go through the indexes of each one separately?

like image 621
user1040563 Avatar asked Nov 18 '11 21:11

user1040563


2 Answers

If you really need the indices you can just do what you said again for the inner list:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:

for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]
like image 104
Claudiu Avatar answered Oct 19 '22 19:10

Claudiu


Try this setup:

a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]

The first brackets reference which nested list you're accessing, the second pair references the item in that list.

like image 40
JAG Avatar answered Oct 19 '22 19:10

JAG