0

So I want to iterate over pairs of subsequent elements. The "pythonic" (I hope at least) way to do it would be:

# `a` is a list of something
for elem_1, elem_2 in zip(a, a[1:]):
    ...

The less pythonic way would probably be something like

for i in range(len(a) - 1):
    elem_1 = a[i]
    elem_2 = a[i + 1]
    # yikes, so much indexing   
    ...

I like how the option 1 looks, but I'm not sure whether this sneaky a[1:] will create a copy of the a list and thus use twice as much memory. Will it? Will it not?

iezepov
  • 455
  • 3
  • 12
  • Yes, list-slicing always creates a new list. Generally, unless your lists are *huge*, this won't matter. – juanpa.arrivillaga Dec 11 '18 at 04:08
  • You can use `itertools.islice` for memory-efficient slicing of arbitrary iterables. so, `list(zip(a, itertools.islice(a, 1, None)))` Do note, though, that `itertools.islice(iterator, n, None)` will go through the first n elements of the iterator, of course. Not a big deal for small lists and small values of n. – juanpa.arrivillaga Dec 11 '18 at 04:10

0 Answers0