How to convert each pair of list into tuple in python

Viewed 58

I want to convert list = [1,4,2,3,0] to list_tup = [(1,4),(4,2),(2,3),(3,0)]. You can see my code below but it outputs [(1,4),(2,3)]. I am wondering how to adjust indices in zip.

list=[1,4,2,3,0]
list_tup = tuple(zip(list[0::2], list[1::2]))
2 Answers

Try zipping the whole list with the list without the first element:

l = [1,4,2,3,0]
print(list(zip(l, l[1:])))

Or use unpack *:

l = [1,4,2,3,0]
print([*zip(l, l[1:])])

They both output:

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

Try Zipping whole list without first element of the list

l = [1,4,2,3,0] print(list(zip(l, l[1:])))

output:

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

Related