You can iterate over multiple sequential values at once by combining iter
and zip
, like so:
values = [ 1, 2, 3, 4, 5, 6 ]
valueIterator = iter( values )
for xCoord, yCoord in zip( valueIterator, valueIterator ):
print( xCoord, yCoord )
Which would output:
1 2
3 4
5 6
This will work in both Python 2 and 3, and can be scaled to iterate over any number of values at a time by adding more iterator arguments to zip
.
For example: for x, y, z in zip( valueIter, valueIter, valueIter ):
.
Or if you need even more without an unreasonably long line:
iterReference = iter( self.values )
iterRefs = [ iterReference ] * 10 # Multiple references to the same iterator
for v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 in zip( *iterRefs )
Besides being more readable, it's also several times more efficient than the range
+ splicing solution:
range + splicing: 4.5734569989144804e-05
iter + zip: 1.8035800009965896e-05
(timeit
with 10000 iterations and a list of 600 values.)
Note that this exhausts the iterator, so if you reference it again, it'll essentially be empty. In which case you can just refer back to the original list if needed.