2

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.

2 Answers 2

2

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 ...:.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.