-4

I want to concatenate a string with every element in a given list of strings:

my_variable = 'Blue'
my_list = ['House', 'Paint', 'Cloth']

How do I concatenate my_variable to every element in the my_list such that I have a new list

my_new_list = ['Blue_House', 'Blue_Paint', 'Blue_Cloth']
Assafs
  • 3,257
  • 4
  • 26
  • 39
JungleDiff
  • 3,221
  • 10
  • 33
  • 57
  • 3
    What have you tried? A simple list comprehension would do this easily. – AChampion Sep 08 '17 at 20:07
  • why you tag `pandas` – BENY Sep 08 '17 at 20:11
  • Welcome to SO, this isn't a code writing service, please make an attempt and come back and ask about any problems that you cannot resolve. Please read [ask] and [mcve] – wwii Sep 08 '17 at 20:12
  • 1
    Possible duplicate of [Appending the same string to a list of strings in Python](https://stackoverflow.com/questions/2050637/appending-the-same-string-to-a-list-of-strings-in-python) – Brad Solomon Sep 08 '17 at 20:15

4 Answers4

3

Or use a list comprehension:

>>> [my_variable + '_' + e for e in my_list]
['Blue_House', 'Blue_Paint', 'Blue_Cloth']
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
1
["_".join([my_variable, i]) for i in my_list]
# ['Blue_House', 'Blue_Paint', 'Blue_Cloth']
pylang
  • 40,867
  • 14
  • 129
  • 121
0

Create a new list and iterate through your original list, appending the original list's entry to the new list with 'Blue_' added to the front with a simple +

my_variable = 'Blue'
my_list = ['House', 'Paint', 'Cloth']

new_list = []
for entry in my_list:
    new_list.append(my_variable + "_" + str(entry))

print new_list
>>>>['Blue_House', 'Blue_Paint', 'Blue_Cloth']
MattWBP
  • 376
  • 1
  • 10
  • I tried but I get: TypeError: cannot concatenate 'str' and 'list' objects – JungleDiff Sep 08 '17 at 20:12
  • It sounds like you're not properly iterating through your list (which contains strings) but are trying to concatenate the list itself with the string. Try running the exact code I sent, I've updated it to work with your example input. – MattWBP Sep 08 '17 at 20:18
-1
my_variable1 = 'Blue'
my_variable2 = 'Red'
my_variable3 = 'Black'
my_list = ['House', 'Paint', 'Cloth']

def mergetwo(a, b, s):
    return s.join((a,b))

def prefix(item, pre):
    return lambda sep: mergetwo(pre,item,sep)

def suffix(item, suf):
    return prefix(suf, item)

def mergewith(alist):
    return lambda position: lambda sep: lambda var: list(map(lambda item: position(item, var)(sep), alist))

def addprefix_underscore_mylist(var):
    return mergewith(my_list)(prefix)('_')(var)

def addsuffix_underscore_mylist(var):
    return mergewith(my_list)(suffix)('_')(var)

print(addprefix_underscore_mylist(my_variable1))
print(addprefix_underscore_mylist(my_variable2))
print(addprefix_underscore_mylist(my_variable3))

print(addsuffix_underscore_mylist(my_variable1))
print(addsuffix_underscore_mylist(my_variable2))
print(addsuffix_underscore_mylist(my_variable3))
englealuze
  • 1,445
  • 12
  • 19