I am creating a python program.
I have a list:
[3, 28, 25, 126, 25, 127]
How can I turn this into a list of tuples, so the list becomes:
[(3,28),(25,126),(25,127)]
It joins 2 elements and makes a tuple.
I am creating a python program.
I have a list:
[3, 28, 25, 126, 25, 127]
How can I turn this into a list of tuples, so the list becomes:
[(3,28),(25,126),(25,127)]
It joins 2 elements and makes a tuple.
>>> L = [3, 28, 25, 126, 25, 127]
>>> zip(L[0::2], L[1::2])
[(3, 28), (25, 126), (25, 127)]
This creates two list slices, with a step width of 2 - one starting from index zero, the second starting from index 1. zip
then creates the tuples with one element of each iterable.
>>> L = [3, 28, 25, 126, 25, 127]
>>> zip(*[iter(L)]*2)
[(3, 28), (25, 126), (25, 127)]