hobo takes the wheel
hobo takes the wheel

Reputation: 131

How do I transform this code into a list comprehension?

I have this code in Python2.7 and I wanna (if possible) transform this code into a list comprehension.

z=[]
if p==1:
    z.append('a')
    if m==2:
        z.append('b')

print ''.join(z)

The problem is it gives me an error (syntax error) when I transformed the code like this:

z=['b' if m==2 'a' if p==1]

print ''.join(z)

Or

z=['a' if p==1 'b' if ==m]

print ''.join(z)

Please let me know if this question has a duplicate. I would appreciate your advice.

Upvotes: 0

Views: 21

Answers (1)

Peter G
Peter G

Reputation: 2821

This is a tricky one. I came up with a solution that uses enumerate and an inline if statement to tell the difference between the two if statements. Honestly, using a list comp for this will probably obfuscate the code and it'd be better to just stick with the simpler if statements you already have.

values = ['a', 'b'] # put the append arguments in here, you can also inline this but I put it apart to make the line shorter
z = [val for idx, val in enumerate(values) if (m==2 and p==1 if idx==1 else p==1)]

Upvotes: 1

Related Questions