0

As above. Example:

a = [('P', 2), ('J, 3'), ('K', 3)]

Required: b = ['P', 'J', 'K'] and c = [2, 3, 3]

Alex Deft
  • 2,531
  • 1
  • 19
  • 34

1 Answers1

3

Try this:

b, c = zip(*the_thing)

Example:

>>> b, c = zip(*[('P', 2), ('J', 3), ('K', 3)])
>>> b
('P', 'J', 'K')
>>> c
(2, 3, 3)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • Okay, that is genuis. Some explanation? Zip takes in lists or iterables in general, right? – Alex Deft Jun 14 '19 at 19:58
  • @AlexDeft, the thing is, it can take [_multiple_ iterables](https://docs.python.org/3/library/functions.html#zip). The asterisk (`*`) unpacks the list into multiple arguments, and then `zip` zips them. BTW, the answer to your question is in the last paragraph of the section about `zip` in the docs) – ForceBru Jun 14 '19 at 20:00
  • One last question, zip returns a zip object. Shouldn't we do this: list(zip(...)) and then unpack it? – Alex Deft Jun 14 '19 at 20:01
  • 1
    @AlexDeft, the zip object is iterable, so you can loop over it and use the `x, y, z = iterable` syntax. – ForceBru Jun 14 '19 at 20:02