Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn flat list into two-tuples [duplicate]

Tags:

python

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.

like image 260
David542 Avatar asked Feb 15 '13 20:02

David542


3 Answers

This is quite short:

zip(input, input[1:])[::2]
like image 131
piokuc Avatar answered Sep 21 '22 17:09

piokuc


In [4]: zip(*[iter(lst)]*2)
Out[4]: [('this', 'is'), ('a', 'list')]
like image 22
root Avatar answered Sep 17 '22 17:09

root


>>> input = ['this', 'is', 'a', 'list']

>>> [(input[i], input[i + 1]) for i in range(0, len(input), 2)]
[('this', 'is'), ('a', 'list')]
like image 33
Rohit Jain Avatar answered Sep 17 '22 17:09

Rohit Jain