6

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.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

9

This is quite short:

zip(input, input[1:])[::2]
piokuc
  • 25,594
  • 11
  • 72
  • 102
7
In [4]: zip(*[iter(lst)]*2)
Out[4]: [('this', 'is'), ('a', 'list')]
root
  • 76,608
  • 25
  • 108
  • 120
  • 1
    Does this work because you are feeding zip the same iterator twice, so after getting the first item from the "first list" the first item from the "second list" is actually the 2nd item in the original list? – flutefreak7 May 07 '15 at 20:00
4
>>> input = ['this', 'is', 'a', 'list']

>>> [(input[i], input[i + 1]) for i in range(0, len(input), 2)]
[('this', 'is'), ('a', 'list')]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525