0

Suppose I have a list l in python defined as:

l = [x1, x2, x3,...,xn-1, xn],

is there an easy way to create a list l1:

l1 = [(x1, x2), (x2, x3),...,(xn-1, xn)]?

Cleb
  • 25,102
  • 20
  • 116
  • 151
  • Possible dupe of http://stackoverflow.com/questions/5434891/iterate-a-list-as-pair-current-next-in-python – Kevin Apr 10 '15 at 13:38

1 Answers1

7

You can use a list comprehension and zip two slices of the list together, which are offset by 1 index

>>> l = list(range(10))
>>> [(a,b) for a,b in zip(l[:-1], l[1:])]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218