Zipping two lists with an offset in Python

Walking my first steps in Python from C, I find myself missing pointers from time to time.

In this case I want to go through a list processing two element at a time, where those elements are step places away. This is my initial approach, but I would be happy to learn a couple alternatives, and their advantages.

v = [0,1,2,3,4,5,6,7,8,9]
step = 3
for x, y in zip( v[:-step], v[step:] ) :
  print("\nx={}, y={}".format(x, y))

I’m interested in what can be done with naked Python alone first. But alternatives from a module, are welcome as well. I want to know which approach is closer to pointer use in C (which was my intent with the code above) in terms of efficiency.


You’re on the right track, but it can be simplified to the following.
Note also that the step variable name could add confusion because Python ranges and slices
have a step attribute — but it’s not what you are doing:

start = 3
for x, y in zip(v, v[start:]):

Also note that syntax like v[start:] creates a new list. If you are
dealing with large data volumes and want to avoid that, you can use

from itertools import islice

v = [0,1,2,3,4,5,6,7,8,9]

start = 3
for x, y in zip(v, islice(v, start, None)):
    print(x, y)

Source : Link , Question Author : xcaliph , Answer Author : FMc

Leave a Comment