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
  • 67,685
  • 6
  • 55
  • 77
makpalan
  • 115
  • 7

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,210
  • 3
  • 24
  • 61
2

Create the item according to it's value -

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

Tom Ron
  • 5,322
  • 2
  • 16
  • 32
2

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

[i + suffix * (i=='a') for i in str_list]
user2390182
  • 67,685
  • 6
  • 55
  • 77