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']
Rather than iterate on the second string just append like
new_list = [el1+'_'+ b for el1 in lst]
Try this:
lst =['ab', 'cd', 'ef']
b = 'are'
new = ["_".join([item, b]) for item in lst]
# ['ab_are', 'cd_are', 'ef_are']
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']
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.