[Tutor] Changing lists in place
Bob Gailer
bgailer at alum.rpi.edu
Mon Apr 17 20:17:18 CEST 2006
Paul D. Kraus wrote:
> I have a list that I want to change in a for loop. It changes in the
> loop but the changes are not persistant outside of the loop.
> I thought lists were mutuable objects
They are.
> so I am a bit confused.
>
> Sample Code....
> #!/usr/bin/env python
> """ Testing lists """
>
> mylist = [ 'One ', ' two', ' three ' ]
> print mylist
> for element in mylist:
element is a variable to which the successive items in mylist are
assigned. element has no "magic" connection to the list.
> element = element.strip()
In order to change a list item you must do something like:
mylist[itemIndex] = element.strip()
So you need both the item's value and its position in the list. That's
what enumerate is for:
for itemIndex, element in enumerate(mylist):
mylist[itemIndex] = element.strip()
> [snip]
More information about the Tutor
mailing list