Iterate through the same list starting from different points in Python

I want to iterate through the same list from two different starting points. I can do this way:

for LayerIndex in range(len( layers ) - 1):
    thisLayer = layers[LayerIndex     ]
    nextLayer = layers[LayerIndex + 1 ]

But I'm sure it should have an more Pythonic way to do this.

Upvotes: -1

Views: 194

Answers (2)

Qfwfq
Qfwfq

Reputation: 11

If the layers are consecutive, you can use itertools.pairwise:

import itertools
for thisLayer, nextLayer in itertools.pairwise(layers):
    ...

Upvotes: 1

Winter Squad
Winter Squad

Reputation: 167

Yes, you can do this, but don't forget the second variable (nextLayer) can't overstep the length of the list/tuple.

Upvotes: -1

Related Questions