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.

Dani AI

Generated

Short answer: a single list comprehension can only produce one list. To get two lists you either produce paired results and split them, run two comprehensions at once, or do a single-pass loop. ’s instinct that “it should be possible” is right in spirit; pointed to the common “pair then unzip” technique. Below are practical alternatives and trade-offs.

A compact, single-expression (but two-iteration) form that's very readable:

a, b = [x * 10 for x in items], [x * 20 for x in items]

If you want to build pairs first and then split them (one pass to build pairs, then fast extraction):

pairs = [(x * 10, x * 20) for x in items]
a = [p for p, _ in pairs]
b = [q for _, q in pairs]

For numeric work where performance matters, a vectorized library is simplest and often fastest:

import numpy as np
arr = np.array(items)
a = (arr * 10).tolist()
b = (arr * 20).tolist()

Notes and cautions: the one-line double-comprehension iterates items twice (fine for small lists). Building a list of pairs uses extra memory for that intermediate list. A true single-pass with minimal memory uses an explicit loop that appends to both lists (best for very large or streaming inputs). Also beware that unpacking with * in a function call (the “unzip” trick) will materialize all arguments at call time, so it can be memory-heavy for large inputs. Choose readability for small data, single-pass for streaming/large data, and vectorized ops for numeric arrays.

Recommended Answers

All 2 Replies

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.