0

For example, I have a list ["lol", "sas", "kes", "al"] and I need to add "Hello" if the element in the list contains a letter "l" and "Goodbye" if element contains "s". I should get ["Hello lol", "Goodbye sas", "Goodbye kes", "Hello al"]. How can I achieve this? Do I need to use two if statements? I am a beginner, and I can add only one element to the list like this:

my_list = ["lol", "sas", "kes"]
new_list = ["Hello, " + x for x in my_list]
new_list
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You can use an if...else expression in your list comprehension:

my_list = ["lol", "sas", "kes"]
new_list = ["Hello, " + x if "l" in x else "Goodbye, " + x for x in my_list]

This is to illustrate the syntax. It doesn't completely meet your requirements. The rest is left as an exercise to the reader.

If your list comprehension gets significantly longer than this, you can rewrite it as a for loop and use the append() function of list. This allows you to break the code onto multiple lines which makes more complex code easier to understand.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268