[Tutor] changing list element in loop

Jim Mooney cybervigilante at gmail.com
Sat Apr 27 12:31:03 CEST 2013


On 27 April 2013 02:55, Amit Saha <amitsaha.in at gmail.com> wrote:
> On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> Why isn't 'e' changing to 'pP here when the vowel list is mutable:
>>
>> vowelList = list('aeiouy')
>>
>> for x in vowelList:
>>     if x == 'e':
>>         x = 'P'
>
> This is because x is really a label for the item in your list. It does
> not represent a reference to the position of element as it occurs in
> the list. For example:


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)
for x in vlist:
    if x[1] == 'e':
        x[0] = 'P'

print(vowels)
#'tuple' object does not support item assignment


More information about the Tutor mailing list