[Tutor] Replacement of items in a list

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 3 Aug 2001 13:27:16 -0700 (PDT)


On Fri, 3 Aug 2001, Andrei Kulakov wrote:

> 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:
> >         x = string.lower(x)
> 
> This doesn't change values in list. for x in list: iterates over
> newly created values that it takes from list. Here's how I'd do it (2.0+):
> 
> >>> lst
> ['ONE', 'TWO', 'THREE']
> >>> newlst = [x.lower() for x in lst]
> >>> newlst
> ['one', 'two', 'three']


Alternatively, you can modify elements in the list if you access the items
by index:

###
def lowercaseList(L):
    for i in range(len(L)):
        L[i] = string.lower(L[i])
###

Doing it by index will allow you to make changes to the list.

By the way, you might want to avoid naming your variables things like
"list" or "str" --- those names are already being used by built-in
functions in Python.  Python will let us redefine what they mean, but in
most cases, this is a very bad idea... *grin*


Hope this helps!