samR
samR

Reputation: 59

Concatenate list of string in Python

Hello enthusiast programmers, It seems I am very bad at manipulating lists in Python (I come from the IDL world, and I really struggle with Python). I have a list of string, say:

mylist =['boring', 'enjoyable', 'great']

and a string, say:

s = 'Python is '

and I want to build the list: ['Python is boring', 'Python is enjoyable', 'Python is great']

mynewlist = s + l

as I would have simply done in IDL, doesn't work of course ... I am not able to do it simply! (i.e. without a loop and intermediate variables)

Thanks for the help!

s.

Upvotes: 2

Views: 122

Answers (2)

Amadan
Amadan

Reputation: 198294

Use map or list comprehensions:

map(lambda x: "Python is " + x, mylist)

["Python is " + x for x in mylist]

Both solutions will do an implicit loop, just like IDL would; it is inevitable to have one in this scenario. But no overt loop like for ...:.

Upvotes: 2

jake77
jake77

Reputation: 2034

that would be:

newlist = [s + x for x in mylist]

You basically carry out the same addition for each element of mylist; the result is a list itself. The way it is done is called list comprehension, one of the most powerful tools for list manipulation.

Upvotes: 2

Related Questions