iNoob
iNoob

Reputation: 1395

Python list concatenation with strings into new list

Im looking for the best way to take a list of stirngs, generate a new list with each item from the previous list concatenated with a specific string.

Example sudo code

list1 = ['Item1','Item2','Item3','Item4']
string = '-example'
NewList = ['Item1-example','Item2-example','Item3-example','Item4-example']

Attempt

NewList = (string.join(list1))
#This of course makes one big string

Upvotes: 1

Views: 80

Answers (4)

Chris_Rands
Chris_Rands

Reputation: 41168

An alternative to list comprehension is using map():

>>> map(lambda x: x+string,list1)
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']

Note, list(map(lambda x: x+string,list1)) in Python3.

Upvotes: 2

Benjamin
Benjamin

Reputation: 2286

concate list item and string

>>>list= ['Item1', 'Item2', 'Item3', 'Item4']
>>>newList=[ i+'-example' for i in list]
>>>newList
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

Use string concatenation in a list comprehension:

>>> list1 = ['Item1', 'Item2', 'Item3', 'Item4']
>>> string = '-example'
>>> [x + string for x in list1]
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example']

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599480

If you want to create a list, a list comprehension is usually the thing to do.

new_list = ["{}{}".format(item, string) for item in list1]

Upvotes: 5

Related Questions