Armangh
Armangh

Reputation: 9

Can i instanciate two lists with one loop if they're in the same object?

If i have two empty lists and i want to populate them with all "a"s and "b"s in the same object, can i do sometihng like:

a, b = [foo.a, foo.b for foo in foo]

Because currently I have them separated into two separate list comprehensions.

a = [foo.a for foo in foo]

b = [foo.b for foo in foo]

And so I was wondering if I can somehow consolidate them into one line and argument.

Upvotes: 0

Views: 62

Answers (3)

ScienceSnake
ScienceSnake

Reputation: 617

You can do it with one loop, but it's not a comprehension

a, b = [], []

for foo in foos:
    a.append(foo.a)
    b.append(foo.b)

I changed your for foo in foo to for foo in foos, which is what I assumed you meant, otherwise the iteration makes very little sense.

Upvotes: 0

Barmar
Barmar

Reputation: 782785

A list comprehension can only create one list. Your code is create a list of tuples (except that the tuple elements need to be in parentheses to prevent a syntax error).

You can unzip this into two lists, though:

a, b = zip(*[(foo.a, foo.b) for foo in foo])

See How to unzip a list of tuples into individual lists? for an explanation of this.

Upvotes: 5

Julian Matthews
Julian Matthews

Reputation: 94

You can always make it one line with a comma. However making it one line, if anything, makes the code less readible.

a, b = [foo.a for foo in foo], [foo.b for foo in foo]

Upvotes: 3

Related Questions