Appending the same string to a list of strings in Python

ghz 3months ago ⋅ 129 views

I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:

list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

*magic*

list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']

I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated.

Answers

You can achieve this easily using list comprehension in Python, which is both concise and readable.

Here’s how you can append the string 'bar' to each element in list1:

list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

list2 = [item + string for item in list1]

print(list2)

Output:

['foobar', 'fobbar', 'fazbar', 'funkbar']

Explanation:

  • The list comprehension [item + string for item in list1] goes through each item in list1 and concatenates the string 'bar' to it.
  • This creates a new list (list2) where each element is the original string from list1 with 'bar' appended.