0

I have an array that looks like this

   [1,2,3,4,5]

and I would like a list of tuples that looks like this:

[(1,2),(2,3),(3,4),(4,5)]

What is the most convenient way to do this in python?

Thanks!

giorgioca
  • 713
  • 1
  • 8
  • 21

2 Answers2

7
zip( a[:-1], a[1:] )

see help(zip) or the website documentation of zip.

Since zip limits itself to the shorter sequence,

zip(a, a[1:])

works too.

EDIT:

Steven brought up the interesting point that if a is very long, doing the implicit copy to get the separate pyObject that is a[1:] is problematic. In this case, you might want to use numpy and its options to get a view on the same data with but a offset.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • 1
    It should be `zip( a[:-1], a[1:] )` – ZdaR Jun 03 '15 at 15:07
  • 1
    May as well reduce it to `zip(a, a[1:])` since it only zips up to the end of the shortest argument. – Kevin Jun 03 '15 at 15:08
  • Your answer is practical and pythonic. However if the OP needs to generate the tuples on the fly, he can use the [recipe](https://docs.python.org/2/library/itertools.html#recipes) for `pairwise` from the `iterools` module docs. This would be useful if the data were coming from a very large in-memory list or a large external file. – Steven Rumbalski Jun 03 '15 at 15:13
  • @StevenRumbalski: Where does hat "needs them on the fly" come from? Op said he "has arrays and need a list of tuples". I appreciate your memory argument, though. – Marcus Müller Jun 04 '15 at 08:46
3

This can be done using list comprehension and list slicing, you iterate over the elements upto len(a) - 1 and on each iteration slice the elements form current_index and the element next to it.

a = [1,2,3,4,5]
b = [tuple(a[i:i+2]) for i in range(len(a)-1)]
print b

>>> [(1, 2), (2, 3), (3, 4), (4, 5)]
ZdaR
  • 22,343
  • 7
  • 66
  • 87