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.

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.

Thanks, this is awesome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.