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!
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!
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.
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)]