-1

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)]
tom
  • 2,335
  • 1
  • 16
  • 30

2 Answers2

2

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

fredtantini
  • 15,966
  • 8
  • 49
  • 55
0

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...

Dan Lenski
  • 76,929
  • 13
  • 76
  • 124