Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

string manipulation in IF statement in Python list comprehension

For the following if statement in this list comprehension, to create the string "sha me" when person == 'sha', it produces an error. It seems that for list comprehensions, only the else part of the if statement can include manipulations. I can rewrite as a for loop/if statement and manipulate when person == 'sha', but I’m unclear why it is not accepted in a list comprehension?

people = ['sha','john','erin']
newlist = [person if person == 'sha' person + ' me' else person + ' Lastname' for person in people]
print(newlist)

produces:

SyntaxError: expected ‘else’ after ‘if’ expression

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

people = ['sha','john','erin']
newlist = [person + ' me' if person == 'sha' else person + ' Lastname' for person in people]
print(newlist)

Or you can use f-string this way:

newlist = [f'{person} me' if person == 'sha' else f'{person} Lastname' for person in people]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading