orangenhaft
orangenhaft

Reputation: 111

Multiple list comprehensions in one line in python

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?

Upvotes: 1

Views: 71

Answers (2)

orangenhaft
orangenhaft

Reputation: 111

first_entries, seconds_entries, third_entries = zip(*result)

works as expected

Upvotes: 3

matszwecja
matszwecja

Reputation: 8086

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?

Upvotes: 0

Related Questions