[Tutor] changing list element in loop

Alan Gauld alan.gauld at btinternet.com
Sat Apr 27 13:33:23 CEST 2013


On 27/04/13 10:49, Jim Mooney 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'


x is just a reference to the object in the list.
When you assign 'P' to x you are making x point at
a new object, you are not doing anything to the
original list.

The list itself is just a sequence of references
to objects. To change the item in the list you
need to change what that list reference is
pointing at.

The enumerate function helps do that by returning
the index as well as the item.

for index,item in enumerate(vowelList):
     if item == 'e':
        vowelLIst[index] = 'P'

Of course for strings there are easier way to do
substitutions using the string methods (replace)
but for general list processing thie above is the usual idiom.

You can also use a while loop obviously:

index = 0
while index < len(vowelList):
    if vowelList[index] == 'e':
       vowelList[index] = 'P'
    index += 1

But a for loop is usually the preferred mechanism.

For this specific use case you could also use a
map() or list comprehension to achieve the same
results:

def f(c): return c if c != 'e' else 'P'
vowelList = map(f,vowelList)   # using map OR...
vowelList = [f(c) for c in vowelList]   # using list comp


HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list