Reputation: 415
I have a matrix of size 10000x20. What's the best way to check for the last iteration when looping through all 10000 rows of the matrix? My solution is:
height = 10000
...
...
for i in range(height):
if i != height - 1:
...
...
else:
...
...
Is this a good way to check for the last item when we work with really long lists?
Upvotes: 0
Views: 61
Reputation: 184211
Loop over all but the last row, then handle the last row separately after the loop.
for i in range(height-1):
# handle most rows here
# we must have at least one row; omit if statement if you know height > 0
if height > 0:
# handle last row using an index of -1, or height-1
I'm assuming you're iterating over the range because you need the index for some purpose. Ordinarily you'd want to avoid that to be Pythonic, but in this case it might be the simplest way to avoid processing the last row in the main loop.
If there is code in common between the cases, i.e. you handle the last row like the rest of them but do something extra with it in addition, you can handle it like this:
for row in matrix:
# common processing for all rows here
if height > 0:
# additional code for final row
In this case you're iterating over the whole list in the for
loop, so you can use for row in matrix
instead of iterating over the range. If you do need the index, the Pythonic way to do this is with enumerate()
:
for i, row in enumerate(matrix):
If you need to duplicate code between the two cases, it might be appropriate to break that out into a function.
Upvotes: 2