Is there a single line expression to accomplish the following:
input = ['this', 'is', 'a', 'list']
output = [('this', 'is'), ('a', 'list')]
My initial idea was to create two lists and then zip them up. That would take three lines.
The list will have an even number of elements.
This is quite short:
zip(input, input[1:])[::2]
In [4]: zip(*[iter(lst)]*2)
Out[4]: [('this', 'is'), ('a', 'list')]
>>> input = ['this', 'is', 'a', 'list']
>>> [(input[i], input[i + 1]) for i in range(0, len(input), 2)]
[('this', 'is'), ('a', 'list')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With