[Tutor] changing list element in loop

Steven D'Aprano steve at pearwood.info
Sat Apr 27 13:16:52 CEST 2013


On 27/04/13 20:31, Jim Mooney wrote:

> Okay, I tried enumerate, but now I get an "immutable" error. So let's
> turn this around since it's getting out of hand for a simple list
> replacement ;')  What's the simplest way to go through a list, find
> something, and replace it with something else?
>
> vowels = 'aeiouy'
> vlist  = enumerate(vowels)

Let's see what that does:

py> print(vlist)
<enumerate object at 0xb7bcdb6c>

That's your first clue that something is wrong. There's no list! So when
you get your index later on, what do you change? You can't write back to
vowels, because that's a string and can't be modified.

Nevermind, let's keep going...


> for x in vlist:

So what's x? It's a tuple, and tuples are immutable. So you can't modify
that either.


>      if x[1] == 'e':
>          x[0] = 'P'

That can't work, and even if it did work, it won't modify vowels, because
that's a string.

The right way to do this is:


vowels = list('aeiouy')  # y is only sometimes a vowel
for index, char in enumerate(vowels):
     if char == 'e':
         vowels[index] = 'P'

print(vowels)  # still as a list
print(''.join(vowels))



-- 
Steven


More information about the Tutor mailing list