[Tutor] changing list element in loop
Amit Saha
amitsaha.in at gmail.com
Sat Apr 27 11:55:58 CEST 2013
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:
>>> a= ['a','e','i']
In the above list, a[0] is 'a', a[1] is 'e' and so on. So, if you want
to change the character 'e' above to 'o', you will have to do:
>> a[1] = 'o'
>>> a
['a','o','i']
Hope that helps. You may find the enumerate() function useful in this
case: http://docs.python.org/2/library/functions.html#enumerate
Best,
Amit.
>
> print(vowelList)
>
> #result: ['a', 'e', 'i', 'o', 'u', 'y']
>
> --
> Jim Mooney
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
--
http://echorand.me
More information about the Tutor
mailing list