[Tutor] Replacement of items in a list
Fri, 3 Aug 2001 15:09:04 -0400
On Fri, Aug 03, 2001 at 12:30:52PM -0600, VanL wrote:
| Why is this?
| :::::::::::::: Begin test.py
| #!/usr/bin/env python
| import string
| lst = ['ONE', 'TWO', 'THREE']
| lst1 = lst[:]
| lst2 = lst[:]
| def replace1(list):
| """ Uses item replacement"""
| for x in list:
The for loop is just a shorthand notation for (except that you have no
access to the 'i')
i = 0
while 1 :
x = list[i]
except IndexError : pass
So what you have as the variable 'x' is a reference to an item in the
list. The list is irrelevant in this function, except as a convenient
way to get to all the various x's
| x = string.lower(x)
Here you change your local variable 'x' to refer to a new string, but
you haven't touched the list at all.
| def replace2(list):
| """Uses position replacement"""
| for x in range(len(list)):
| list[x] = string.lower(list[x])
This works because you have modified the list as opposed to simply
adjusting a local reference.