Thor Correia
Thor Correia

Reputation: 1588

How to for loop in reverse?

I'm making a water simulation program, and I need it to do a for loop through y, x. But I need it to check the most bottom y first, then up. This is my lvl:

lvl = [[0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]]

I need it to check lvl[4] and then lvl[3], lvl[2], etc. Please help!

NB: I'm using nested for loops, so I can check y, x.

Upvotes: 2

Views: 8553

Answers (2)

jdiemz
jdiemz

Reputation: 539

If you're using for loops, you can use range to generate a reversed sequence to index lvl with.

>>> range(4,-1,-1)
[4, 3, 2, 1, 0]

i.e., maybe something similar to:

>>> for i in range(4,-1,-1):
...     print lvl[i]
...
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
>>>

Upvotes: 3

Makoto
Makoto

Reputation: 106470

You can use the reversed built-in method to reverse the ordering of your list of lists:

for li in reversed(lvl):
    print li

Output:

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]

Upvotes: 9

Related Questions