Search code examples
pythonlist-comprehension

Python list comprehension with multiple conditions


I have a list of strings

str_list = ['a', 'b', 'c']

and want to add a suffix

suffix = '_ok'

when the string value is 'a'.

This works:

new_str_list = []
for i in str_list:
    if i == 'a':
        new_str_list.append(i + suffix)
    else:
        new_str_list.append(i)

new_str_list
# ['a_ok', 'b', 'c']

How can I simplify this with a list comprehension? Something like

new_str_list = [i + suffix for i in str_list if i=='a' ....

Solution

  • [i + suffix if i == 'a' else i for i in str_list]
    

    Putting if after the for as you tried is for skiping values.

    In your case you don't skip values but process them differently.