2

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.

miik
  • 663
  • 1
  • 8
  • 23
  • 1
    Before you ask your next question, you ought to do some research. If that doesn't answer your question, then [try something yourself](http://mattgemmell.com/2008/12/08/what-have-you-tried/) before you ask. – Volatility Apr 23 '13 at 07:29

2 Answers2

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

Eric
  • 95,302
  • 53
  • 242
  • 374
  • Note that this is not as efficient as my solution since you are making two shallow copies :P – jamylak Apr 23 '13 at 07:39
  • 1
    Seconding @jamylak, you're not creating iterators, you're immediately creating shallow copies of the subsets being sliced. For very short lists though, this may actually be faster from minimised function calls (but at that point, the performance diff is negligible anyway), but some benches I saw a few months back for similar iterator vs. generate subsets upfront scenarios show iterators rapidly become the optimal solution for anything but the shortest of lists. – Endophage Apr 23 '13 at 07:42
7
>>> 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?

Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 2
    That one's a bit opaque. Could you explain it? – Kyle Strand Apr 23 '13 at 07:31
  • 1
    @Kyle Strand: It's well explained in the documentation: http://docs.python.org/3.3/library/functions.html#zip – aldeb Apr 23 '13 at 07:32
  • @KyleStrand Also added a link to that question – jamylak Apr 23 '13 at 07:34
  • 3
    I'd note that the really important, non-obvious bit here is that `[iter(L)]*2` creates 2 pointers (I won't call them labels as they're not named, just indexed in a list) to the same iterator instance so when doing the zip, the same iterator instance is getting called to generate both elements in the tuple, causing the desired grouping by default. – Endophage Apr 23 '13 at 07:36
  • Ah. That's quite slick. – Kyle Strand Apr 23 '13 at 07:37