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
>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]