3

One basic question in list comprehension as i am starting on that,

can a list comprehension return two arrays?

like I was trying to convert my code to list comprehension

b=[10,2,3]
c=[10,11,12]
d=[]
f=[]
a=10
for i in b:
    if a>i:
        for j in c:
            d.append(j)

print d

I am able to convert the above code using list comprehension as

print [j  for i in b if a>i  for j in c ]

But now I want to add an extra else block to my initial code and looks like

b=[10,2,3]
c=[10,11,12]
d=[]
f=[]
a=10
for i in b:
        if a>i:
            for j in c:
                d.append(j)
        else:
          f.append(i)
print d
print f

d=[10, 11, 12, 10, 11, 12]
f=[10]

is there any way I can add this extra else to my initial list comprehension?

2 Answers 2

7

You can't use a list comprehension for your second example, because you are not building a single list. List comprehensions build one list object, not two.

You could use two separate list comprehensions:

d = [j for i in b if a > i for j in c]
f = [i for i in b if a <= i]

or you could simplify your loops a little by using list.extend() or += augmented assignments:

for i in b:
    if a > i:
        d.extend(c)
    else:
        f.append(i)

or

for i in b:
    if a > i:
        d += c
    else:
        f.append(i)
Sign up to request clarification or add additional context in comments.

2 Comments

You can't use a list comprehension for your second example. Challenge accepted.
@EricDuminil: yes, you can produce multiple sequences and unpack. You can use zip() too. It is never readable, however.
2

To answer your question :

Can a list comprehension return two arrays?

Yes, it can:

>>> [[1] * n for n in [3, 5]]
[[1, 1, 1], [1, 1, 1, 1, 1]]
>>> d, f = [[1] * n for n in [3, 5]]
>>> d
[1, 1, 1]
>>> f
[1, 1, 1, 1, 1]

Just for fun, here's a one-liner to define both d and f:

d, f = [[j for i in b if f(i) for j in g(i)] for (f, g) in [(lambda x: x < a, lambda x: c), (lambda x: x >= a, lambda x: [x])]]

It's obviously a bad idea, though, and @MartijnPieters's answer is preferable.

1 Comment

You've answered the question, shown code and outputs, and simultaneously shown just because one can does not mean one should. Challenge accomplished!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.