Let's say I want to built a list of tuples from a given list. Is there any way of doing this with a list comprehension, or do I need to resort to a for loop?
[a,b,c,d,e] => [(a,b),(b,c),(c,d),(d,e)]
Let's say I want to built a list of tuples from a given list. Is there any way of doing this with a list comprehension, or do I need to resort to a for loop?
[a,b,c,d,e] => [(a,b),(b,c),(c,d),(d,e)]
You could do:
>>> l = ['a','b','c','d','e']
>>> [(l[i],l[i+1]) for i in range(len(l)-1)]
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
with zip:
>>> zip(l,l[1:])
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
-- Edited according to comments
Not directly, but it's easy to do given a loop index, e.g.:
l='''a,b,c,d,e'''.split(',')
[(l[x],l[x+1]) for x in range(len(l)-1)]
Outputs:
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]
EDIT: Looks like several of us came up with this identical solution simultaneously...