Uliysess Uliysess - 3 years ago 220
Python Question

Loop through 2D array in reverse

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

Answer Source

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...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download