krish
krish

Reputation: 59

How to add a new word to the string values in a list?

I have an issue with lists, I have a list lst =['ab', 'cd', 'ef']. Now I want to add a string ('are')to end of each string value of the list. I tried but it is getting added letter by letter, how to add the whole word to end of each string value in the list?

My code:

lst =['ab', 'cd', 'ef']
b = 'are'
new_list =  [el1+'_'+el2 for el2 in b for el1 in lst]

It gives:

new_list = ['ab_a', 'cd_a', 'ef_a','ab_r', 'cd_r', 'ef_r','ab_e', 'cd_e', 'ef_e']

Excepted output:

new_list = ['ab_are', 'cd_are', 'ef_are']

Upvotes: 0

Views: 62

Answers (4)

James Francis
James Francis

Reputation: 36

Just iterate in list

    lst = ["ab", "cd", "ef"]
    b = "are"
    iterated_list = [i + " " + b for i in lst]
    print(iterated_list)

    

Another option would be the following below:

   lst = ["ab", "cd", "ef"]
   b = "are"
   iterated_list = []
   for i in lst:
       iterated_list.append(i + " " + b)

   print(iterated_list)
   

Upvotes: 1

Kien Nguyen
Kien Nguyen

Reputation: 2691

You are iterating through both list and string. Just iterate through the list:

lst =['ab', 'cd', 'ef']
b = 'are'
new_list =  [el + '_' + b for el in lst]
print(new_list)

Output:

['ab_are', 'cd_are', 'ef_are']

Upvotes: 1

aymenim
aymenim

Reputation: 146

Rather than iterate on the second string just append like

new_list =  [el1+'_'+ b for el1 in lst]

Upvotes: 2

Meny Issakov
Meny Issakov

Reputation: 1421

Try this:

lst =['ab', 'cd', 'ef']
b = 'are'

new = ["_".join([item, b]) for item in lst]

# ['ab_are', 'cd_are', 'ef_are']

Upvotes: 1

Related Questions