Padraic Cunningham
Padraic Cunningham

Reputation: 180391

getting two values using comprehension

Is it possible to yield the following using comprehension, I have tried getting both values a,b etc.. but the only way I know is through indexing and when I do that I get string index out of range.

path = ['a', 'b', 'c', 'd', 'e']

--

a, b
b, c
c, d
d, e

Upvotes: 1

Views: 82

Answers (3)

Gareth Latty
Gareth Latty

Reputation: 88977

The best way to achieve this is not through a list comprehension, but zip():

advanced = iter(path)
next(advanced, None)
for item, next_item in zip(path, advanced):
    ...

We produce an iterator over the values, advance it by one so we start with the second value, then loop through the original list and the advanced one at the same time using zip().

Upvotes: 3

jamylak
jamylak

Reputation: 133504

itertools pairwise recipe works on any iterable

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

path = ['a', 'b', 'c', 'd', 'e']
>>> for x, y in pairwise(path):
    print x, y


a b
b c
c d
d e
>>> list(pairwise(path))
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

You can use zip here:

>>> lis =  ['a', 'b', 'c', 'd', 'e']
>>> for x,y in zip(lis,lis[1:]):
...     print x,y
...     
a b
b c
c d
d e

Upvotes: 5

Related Questions