2

I have a list containing various strings, and I want to be able to choose a particular element in the list, and concatenate it with a new string.

I thought this might do it:

checklist = [[0] + 'test' for [0] in checklist]

But it doesn't work. Any suggestions?

1
  • 2
    checklist[index] += 'test' should work. Just make sure that you have the index you want to modify in the index variable. Commented Jul 14, 2014 at 12:37

2 Answers 2

3

Select the string using its index and add the string to it using the + operator

checklist = ['a','b','c']
checklist[1] += 'd'
print checklist
#['a', 'bd', 'c']
Sign up to request clarification or add additional context in comments.

2 Comments

Correct solution, but there is nothing to do with slice notation here so I'm not sure why you mention it. This is just ordinary indexing, list.__iadd__ to be precise.
@wim wooops, thanks for correcting me on that one :)
1

The free variable in a list comprehension, i.e. the symbol between for and in in your code, must be a valid python identifier.

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.