0

I want to go through a 2D array in reverse. Thats is why I use reversed() but I get an error that says

list indices must be integers, not list

Array example:

labirynth = [
[1,1,1,1,1,1,1],
[1,0,0,0,1,0,1],
[1,0,1,0,0,0,1],
[1,1,1,1,1,1,1]
]

My current solution:

for i in reversed(labirynth):
    for j in reversed(labirynth[i]):
        #do stuff
bfontaine
  • 18,169
  • 13
  • 73
  • 107
Uliysess
  • 579
  • 1
  • 8
  • 19
  • Possible duplicate of [Rotating a two-dimensional array in Python](https://stackoverflow.com/questions/8421337/rotating-a-two-dimensional-array-in-python) – Torxed Sep 28 '17 at 08:34

2 Answers2

1

There is no need to access the list with []. The outer for loop already returns the list. You can just do

for i in reversed(labirynth):
    for j in reversed(i):
        # do stuf...
bgfvdu3w
  • 1,548
  • 1
  • 12
  • 17
0

You probably want

for i in reversed(labirynth):
  for j in reversed(i):
    # do stuff

here's an interactive demo:

>>> labirynth = [
[1,1,1,1,1,1,1],
[1,0,0,0,1,0,1],
[1,0,1,0,0,0,1],
[1,1,1,1,1,1,1]
]
... ... ... ... ...
>>> for i in reversed(labirynth):
...    print i
... 
[1, 1, 1, 1, 1, 1, 1]
[1, 0, 1, 0, 0, 0, 1]
[1, 0, 0, 0, 1, 0, 1]
[1, 1, 1, 1, 1, 1, 1]
>>> for i in reversed(labirynth):
...   for j in reversed(i):
...     print j
... 
1
1
1
... continues
jq170727
  • 13,159
  • 3
  • 46
  • 56