0

Assume that I have a list:

l = ['foo', 'bar', 'baz']

How to append pre to bar to have:

l = ['foo', 'prebar', 'baz']

?

4 Answers 4

2

Lists are mutable; strings are not. Therefore, assuming you know the index of the string you want to change:

l = ['foo', 'bar', 'baz']
i = 1
l[i] = 'pre' + l[i]

This gives l = ['foo', 'prebar', 'baz'].

Using a list comprehension constructs a whole new list in memory, which is wasteful of resources (though immaterial for small lists). This method modifies the existing list in place.

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

1 Comment

Using a slice assignment with a generator expression eliminates the objection of creating a new list, but I agree that directly modifying the desired item is the best approach when possible. If you don't know what item you want to change, that's what list.index() is for!
1

You can use + operand to concatenate strings together.So you can use a list comprehension to loop over your list and change the item that is equal with 'bar' :

>>> l1=['pre'+i if i=='bar' else i for i in l1]
>>> l1
['foo', 'prebar', 'baz']

1 Comment

Thanks Kasra. BTW, love your motto! :)
0

Alternatively to the other answer you can also alter the list directly:

l[1] = l[1] + "bar"

Comments

0
l=['pre'+i if i=='bar' else i for i in l]
l
['foo', 'prebar', 'baz']

result

['foo', 'prebar', 'baz']

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.