Multiple list comprehensions in one line in python

Question:

I have the following code in Python 3.9:

first_entries = [r[0] for r in result]
seconds_entries = [r[1] for r in result]
third_entries = [r[2] for r in result]

where result is a list of tuples of the following form:

result = [(x1,x2,x3),(y1,y2,y3),...]

Is there a way to write this into one line and iterate over result only once?

Asked By: orangenhaft

||

Answers:

tups = [(1,2,3), (4,5,6), (7,8,9), (10,11,12)]

first_entries, second_entries, third_entries = zip(*[(tup[0], tup[1], tup[2]) for tup in tups])

print(first_entries) # (1, 4, 7, 10)

Do you really need to separate those results into 3 lists though?

Answered By: matszwecja

first_entries, seconds_entries, third_entries = zip(*result)

works as expected

Answered By: orangenhaft
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.