Python list comprehension, unpacking and multiple operations Python list comprehension, unpacking and multiple operations python python

Python list comprehension, unpacking and multiple operations


Use a nested list comprehension:

result = [a for tup in y for a in tup]

Example:

>>> x = range(10)>>> y = [(i,j**2) for i,j in zip(x,x)]>>> [a for tup in y for a in tup][0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]

This will work fine for your more general case as well, or you could do it all in one step:

y = [a for i in x for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i))]

In case the nested list comprehensions look odd, here is how this would look as a normal for loop:

y = []for i in x:    for a in (i, sqrt(i), i**3, some_operation_on_i, f(i), g(i)):        y.append(a)


>>> import itertools>>> list(itertools.chain.from_iterable(y))[0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]