Rohan Bhattacharyya Rohan Bhattacharyya - 23 days ago 6
Python Question

Query on for loop in List of Lists in Python

Why is the first code not giving the desired result of 5,6,1 if I am using range (0,le). I had to use (-1,le) to get all the values of the last column. If I use normal lists the for loop works fine.

def result( game ):
print game
le = len(game)-1
print le
for i in range(0,le):
m = game[i][le]
print m

winner = [[2, 2, 5],[2, 1, 6],[2, 1, 1]]
result(winner)


Outputs:

[[2, 2, 5], [2, 1, 6], [2, 1, 1]]
2
5
6


Second version:

def result( game ):
print game
le = len(game)-1
print le
for i in range(-1,le):
m = game[i][le]
print m

winner = [[2, 2, 5],[2, 1, 6],[2, 1, 1]]
result(winner)


Outputs:

[[2, 2, 5], [2, 1, 6], [2, 1, 1]]
2
1
5
6


Thanks all for your answers.

One other question regarding the same code --

Can you clarify another thing for me? Say if I use the below in the above code -->

le = len(game)

print le

for i in range(0,le):

Why am I getting the following error?

3
Traceback (most recent call last):

File "main.py", line 10, in

result(winner)

File "main.py", line 6, in result

m = game[i][le]

IndexError: list index out of range

Answer

As @Itay has pointed out, range doesn't include the last value. You just need to change your loop to:

for i in range(0,le+1):

for it to loop through all nested lists in the correct order.

By the way: Your second solution is also not giving you your desired solution if you look closely. If you start your range at -1 you are printing the value game[-1][le] which is the same as game[2][le]. So you're essentially starting with the last row and then going to the first and second row in your second solution.