0

I need help with the list comprehension equivalent for the below normal loop code

a = [1,2,3]
b = []
for i in a :
    if i == 2 :
        b.append(i*2)
    else :
        b.append(i)

# the below list comprehension is filtering the list i don't know how to change it correctly
print([n*2 for n in a if n == 2 ] )

print(b)

3 Answers3

2

You can use Python's "ternary" (I don't know the name of it)

[n*2 if n == 2 else n for n in a]
Daniel Garcia
  • 462
  • 3
  • 8
1

Use an else statement, you need to put the for keyword at the end of the list comprehension:

[n*2 if n == 2 else n for n in a]
frab
  • 1,162
  • 1
  • 4
  • 14
0

There is another way of doing it:

[n + n*(n==2) for n in a] 
Tugay
  • 2,057
  • 5
  • 17
  • 32