-1

Is there a function in the standard library, that can generate an iterable of 2-tuples of an iterable that is guaranteed to have an even amount of elements?

INPUT = 'ABCDEF'
OUTPUT = [('A', 'B'), ('C', 'D'), ('E', 'F')]

I could not find anything fitting within itertools.

Richard Neumann
  • 2,986
  • 2
  • 25
  • 50
  • 2
    ``list(zip(INPUT[::2], INPUT[1::2]))``, here is [`dupe`](https://stackoverflow.com/a/4988012/4985099) – sushanth Aug 27 '20 at 13:47
  • Doesn't the `grouper` recipe **in `itertools`** do that? – superb rain Aug 27 '20 at 13:47
  • 1
    `OUTPUT = list(zip(*[iter(INPUT)]*2))` – inspectorG4dget Aug 27 '20 at 13:47
  • @inspectorG4dget Thanks. I think I overcomplicated this in my head. – Richard Neumann Aug 27 '20 at 13:52
  • The referred question is old and refers to lists only. I don't want lists in general. Furthermore it refers to the use of `izip()`, which is no longer available. – Richard Neumann Aug 27 '20 at 13:56
  • [Read the answers, not the question](http://geek-and-poke.com/geekandpoke/2016/11/27/good-questions). [Tihs answer](https://stackoverflow.com/a/30039300/5067311) is spot on, and has a link to docs. Yes, yes, it has an unfortunate `i` in `izip`, and the link is to python 2 docs. It takes one character to fix both, [here's the modern doc link](https://docs.python.org/3/library/itertools.html#itertools-recipes). This doesn't need a duplicate question. – Andras Deak -- Слава Україні Aug 27 '20 at 14:12

1 Answers1

-1

Try this

INPUT = 'ABCDEF'
OUTPUT = list(zip(INPUT[0::2], INPUT[1::2]))
Kuldip Chaudhari
  • 1,112
  • 4
  • 8