1

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
2
  • NewList = [x + string for x in list1] Commented Sep 14, 2016 at 9:56
  • thanks for all the prompt responses. Although all the proposed answers are technically correct I prefered @eugene y Commented Sep 14, 2016 at 10:35

4 Answers 4

5

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]
Sign up to request clarification or add additional context in comments.

Comments

3

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']

Comments

2

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.

Comments

1

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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.