[Tutor] changing list element in loop

Amit Saha amitsaha.in at gmail.com
Sat Apr 27 12:38:51 CEST 2013


On Sat, Apr 27, 2013 at 8:31 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> 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

The enumerate function returns you a tuple consisting of the 'index'
of the element and the element itself. So, you have to store the two
values individually. For example, here is what I did to achieve what
you want to:

>>> x=['a','e','i']
>>> for index, item in enumerate(x):
    if item == 'e':
        x[index]='P'


>>> x
['a', 'P', 'i']

In your attempt you were attempting to change the 'tuple' itself,
which is not what you want and which is not possible - tuples are
immutable.

I hope that makes things a little clearer?

Best,
Amit.



--
http://echorand.me


More information about the Tutor mailing list