2
votes

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.

2
Before you ask your next question, you ought to do some research. If that doesn't answer your question, then try something yourself before you ask. - Volatility

2 Answers

11
votes
>>> 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.

7
votes
>>> L = [3, 28, 25, 126, 25, 127]
>>> zip(*[iter(L)]*2)
[(3, 28), (25, 126), (25, 127)]

How does zip(*[iter(s)]*n) work in Python?