0

Hi guys,

This feels like something that should be possible in Python, and something that I feel like I should know how to do.

Image I have a list of numbers:

items=[10,20,30]

Let's say I wanted iterate over them and define two new variables, a and b.

a=[]
b=[]
for item in items:
  a.append(item*10)
  b.append(item*20)

I can also do this in two list comprehensions:

a=[item*10 for item in items]
b=[item*20 for item in items]

It feel like I should be able to do this in one single expression. Something like:

a,b=[(item*10),(item*20) for item in items]

Is this possible?

Thanks.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by hughesadam_87
2

Yes it is possible:

a, b = zip(*(((item*10),(item*20)) for item in items))

but it gives tuples instead of lists. If you want lists, you can write

a, b = (list(x) for x in zip(*(((item*10),(item*20)) for item in items)))

another way is

a, b = (list(item * x for item in items) for x in (10, 20))

The last one looks better, but it works only if items is a list or a tuple, not any iterable.

Edited by Gribouillis

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.