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
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to