Jonathan
Jonathan

Reputation: 11321

How can I replace parts of strings in a list?

I want to replace part of a string in a list in python 2.7, but this doesn't work the way I expect:

>>> list = ['apples', 'oranges', 'bananas']
>>> for item in list: 
...  item=item.replace('app', 'spam') 
... 
>>> list
['apples', 'oranges', 'bananas']

I expected the output to be: ['spamles', 'oranges', 'bananas'].

What's the right way of doing the above? I know I can probably make a new list and add each item to the new list individually, but that sounds like a lot of work and might require twice the memory.

Upvotes: 0

Views: 117

Answers (3)

roippi
roippi

Reputation: 25954

for item in list: 

This creates a new reference (item) to each successive element in your list. You are then rebinding your reference item to something else, and then throwing that ref away.

I know I can probably make a new list and add each item to the new list individually, but that sounds like a lot of work and might require twice the memory.

Premature optimization is the root of.. some evil. Probably not all evil, but some subset of it.

But seriously, the memory overhead of temporarily creating a list of 3 (or even 3 thousand) strings is not worth thinking about. Just make a new list:

li = ['apples', 'oranges', 'bananas']
li = [x.replace('app','spam') for x in li]
#li = ['spamles', 'oranges', 'bananas']

(don't name your lists list, it shadows the built-in)

If you absolutely, positively have to mutate your list in-place:

for i,x in enumerate(li):
    li[i] = x.replace('app','spam')

And while this doesn't create a new list (temporarily saving memory), it is actually going to be slower than the list-comprehension version, so the "optimization" really didn't get you anywhere.

Upvotes: 1

karthikr
karthikr

Reputation: 99620

Please note list is not a good local variable name.

The reason your code is not working is, you are not replacing the corresponding element in the loop, you are just assigning it to the local variable.

Try this:

x = ['apples', 'oranges', 'bananas']
for i, item in enumerate(x): 
    item=item.replace('app', 'spam') 
    x[i] = item
    #Or just 
    #x[i] = item.replace('app', 'spam') 

Demo:

>>> x = ['apples', 'oranges', 'bananas']
>>> for i, item in enumerate(x): 
...     item=item.replace('app', 'spam') 
...     x[i] = item
... 
>>> x
['spamles', 'oranges', 'bananas']
>>> 

Alternatively, you can use a list comprehensions:

>>> x =  ['apples', 'oranges', 'bananas']
>>> x = [a.replace("app", "spam") for a in x ]
>>> x
['spamles', 'oranges', 'bananas']
>>> 

Upvotes: 5

shx2
shx2

Reputation: 64298

You just reassign to the variable named item, when what you want is to assign to the list-item:

for i, item in enumerate(list):
    list[i] = item.replace('app', 'spam') 

This code is for demonstration only. The real solution is using a list comprehension, like in @karthikr's answer.

Upvotes: 1

Related Questions