How do I create a single list of tuple such as B_tuple_list = [(3,2), (2,1), (1,0), (0,5), (5,4)]
from a single python list such as A_python_list = [3, 2, 1, 0, 5, 4]
.
Thank you.
May be you can try something like below with list comprehension
:
a_list = [3, 2, 1, 0, 5, 4]
tuple_list = [(a_list[i], a_list[i+1]) for i in range(len(a_list)-1)]
print(tuple_list)
Result:
[(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
You can also use zip
l = [3, 2, 1, 0, 5, 4]
print(list(zip(l, l[1:])))
# [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
The solution provided in the itertools recipes uses almost no intermediate storage:
from itertools import tee
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return list(zip(a, b))
print(pairwise([1, 2, 3, 4])) # [(1, 2), (2, 3), (3, 4)]
By removing the cast to a list
, this can be made to return a light-weigth iterator.
Use list comprehensions.
>>> a = [3, 2, 1, 0, 5, 4]
>>> b = [(a[x], a[x+1]) for x in range(len(a))]
>>> print b
[(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
Using zip
:
a_list = [3, 2, 1, 0, 5, 4]
tuple_list = [(x, y) for x, y in zip(a_list, a_list[1:])]
# [(3, 2), (2, 1), (1, 0), (0, 5), (5, 4)]
Or simply,
tuple_list = list(zip(a_list, a_list[1:]))