0

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' ....
user2390182
  • 72,016
  • 6
  • 67
  • 89
makpalan
  • 135
  • 9

3 Answers3

4
[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.

log0
  • 10,489
  • 4
  • 28
  • 62
2

Create the item according to it's value -

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

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
2

A concise option making use of fact that False == 0:

[i + suffix * (i=='a') for i in str_list]
user2390182
  • 72,016
  • 6
  • 67
  • 89