1

I came across a question were someone wanted to generate list3 = [1, 0, 1, 0, 0] for list1 = [0, 1, 0, 0, 1] and list2 = [0, 1, 0, 1, 1].

If one would zip(list1, list2) therefore only zip(0, 0) would generate 1 for list3.

I want to express the subsequent code by a list comprehension:

L3 = []
for x in zip(L1, L2):
    if sum(x) == 0:
        L3.append(1)
    else:
        L3.append(0)
print L3 

I can get the same output by using this list comprehension:

print [int(sum(x)==0) for x in zip(L1, L2)]

I would like to know if there is a way to express the if/else condition of the initial code block in a list comprehension more literally. I can understand this question might be considered superfluous as the if/else condition naturally is comprised, but alternatives posted could be very useful to me.

petruz
  • 533
  • 3
  • 11

2 Answers2

5

You could use a conditional expression:

print [1 if sum(x) == 0 else 0 for x in zip(list1, list2)]

Here, 1 if sum(x) == 0 else 0 directly expresses the condition.

For more information, see Does Python have a ternary conditional operator?

Another alternative is to factor out the logic into a function, and call the function from the list comprehension. This would allow the logic to use any flow control statements (conditional statements, loops etc).

Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970
1
L1,L2 = [0, 1, 0, 0, 1], [0, 1, 0, 1, 1]
# map and lambda 
L3 =  map(lambda x: 1 if not sum(x) else 0, zip(L1, L2))
print L3
# [1, 0, 1, 0, 0]
Ari Gold
  • 1,386
  • 10
  • 16