Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python list comprehension in nested loops

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?

like image 315
syam Avatar asked Sep 27 '26 00:09

syam


2 Answers

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)
like image 163
Martijn Pieters Avatar answered Sep 29 '26 12:09

Martijn Pieters


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.

like image 37
Eric Duminil Avatar answered Sep 29 '26 13:09

Eric Duminil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!