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.

3
  • And what if your list have odd number of elements? Commented Feb 15, 2013 at 20:20
  • You can ignore that for now. Commented Feb 15, 2013 at 20:20
  • Your original plan is fine. I'm sure you could hammer it into one ugly line. Commented Feb 15, 2013 at 20:21

3 Answers 3

9

This is quite short:

zip(input, input[1:])[::2] 
Sign up to request clarification or add additional context in comments.

5 Comments

The question has been marked as a duplicate, but I have't seen this answer yet :) I must say I like it...
Note: does not work in python3. See root's answer for a python3 solution.
Interesting, thanks.
Try zip(input[::2], input[1::2]) for python3 (inspired by your answer)
@NorthIsUp nice, thanks!
7
In [4]: zip(*[iter(lst)]*2) Out[4]: [('this', 'is'), ('a', 'list')] 

1 Comment

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?
4
>>> input = ['this', 'is', 'a', 'list'] >>> [(input[i], input[i + 1]) for i in range(0, len(input), 2)] [('this', 'is'), ('a', 'list')] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.