Ad

How To Separate A Tuple Into Two Independant Lists?

- 1 answer

I would like to separate the following tuple into two lists

(('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), 
 ('fear', 25.071))

I want my lists to look like the following:

a = ('happy', 'neutral', 'neutral', 'happy', 'fear')
b = (5.001, 10.004, 15.006, 20.071, 25.071)

The split() method is not working on this.

Ad

Answer

Here comes your new hero, the zip function!

l = (('happy', 5.001), ('neutral', 10.004), ('neutral', 15.006), ('happy', 20.071), ('fear', 25.071))
a, b = zip(*l)

For future usages, we could say that it works in two different modes:

  • zip(*iterable) generates n iterables (being n the size of every tuple in the iterable), where every iterable contains the ith element of each tuple (the example of my answer).
  • zip(iterable_1, ..., iterable_n) generates a single iterable where every element is a tuple of size n containing the element of every iterable at the corresponding index.
Ad
source: stackoverflow.com
Ad