15

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

Generally I just write:

for i in range(len(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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user1040563
  • 5,121
  • 9
  • 34
  • 36
  • 1
    You need to rewrite your question and make it clear. Your use of “indexes” is suspect; perhaps you meant “items”? – tzot Nov 19 '11 at 21:36
  • This is a question about walking nested lists, the [other](http://stackoverflow.com/questions/8184768/comparing-lists-python) is about comparing nested lists. – Kev Nov 20 '11 at 15:37

6 Answers6

25

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]
nachiketsd
  • 41
  • 8
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 3
    this was helpful but i hate how you used variables "l', i and 1. so freakin' hard to read and differentiate I dont know why people do this for their examples. – Aspen Nov 15 '18 at 17:10
5

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.

4444
  • 3,541
  • 10
  • 32
  • 43
JAG
  • 51
  • 1
  • 1
2

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item
lc2817
  • 3,722
  • 16
  • 40
0

The question title is too wide and the author's need is more specific. In my case, I needed to extract all elements from nested list like in the example below:

Example:

input -> [1,2,[3,4]]
output -> [1,2,3,4]

The code below gives me the result, but I would like to know if anyone can create a simpler answer:

def get_elements_from_nested_list(l, new_l):
    if l is not None:
        e = l[0]
        if isinstance(e, list):
            get_elements_from_nested_list(e, new_l)
        else:
            new_l.append(e)
        if len(l) > 1:
            return get_elements_from_nested_list(l[1:], new_l)
        else:
            return new_l

Call of the method

l = [1,2,[3,4]]
new_l = []

get_elements_from_nested_list(l, new_l)
lfvv
  • 1,509
  • 15
  • 17
-1
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in lists:
    for numbers2 in numbers:
        results.append(numbers2) 
  return results
print flatten(n)

Output: n = [1,2,3,4,5,6,7,8,9]

  • This snippet is an unnecessary re-invention of [`chain.from_iterable`](https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable) –  May 17 '18 at 16:13
-1

I think you want to access list values and their indices simultaneously and separately:

l = [[2,2,2],[3,3,3],[4,4,4],[5,5,5]]
l_len = len(l)
l_item_len = len(l[0])
for i in range(l_len):
    for j in range(l_item_len):
        print(f'List[{i}][{j}] : {l[i][j]}'  )