1

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.

niraj
  • 17,498
  • 4
  • 33
  • 48
Vondoe79
  • 313
  • 4
  • 22

5 Answers5

3

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)]
niraj
  • 17,498
  • 4
  • 33
  • 48
3

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)]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
2

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.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

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)]
jowabels
  • 122
  • 1
  • 9
1

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:]))
Austin
  • 25,759
  • 4
  • 25
  • 48