changing names of items in a list

Diez B. Roggisch deets at nospam.web.de
Wed Mar 19 10:42:33 EDT 2008


royG wrote:

> hi
> i am trying to rename extension of files in a directory..as an initial
> step i made a method in
> 
> class ConvertFiles:
>      def __init__(self,infldr,outfldr):
>              self.infldr=infldr
>              self.outfldr=outfldr
>              self.origlist=os.listdir(infldr)
> ....
>      def renamefiles(self,extn):
>              for x in self.origlist:
>                      x=x+"."+extn
> 
> ...
> 
> later when i print self.origlist  i find that the elements of list are
> unchanged..even tho  a print x  inside the renamefiles()  shows that
> extn is appended to x  ..
> why does this happen?

Because a piece of code like this

x = some_list[index]
x = something_else()

doesn't change the object itself, just rebinds x to a new object. That the
old object stored in x happened to be referenced in a list as well - who
cares?

So either your members of origlist become mutables - then you have to alter
them, and then they will be reachable from the list. Like this:

class Foo(object):
    def __init__(self):
        pass

l = [Foo() for _ in xrang(10)]

f = l[0]
f.bar = "baz"

print l[0].bar

Or you rebind the list itself, or it's index under work - like this:

for i, item in enumerate(l):
    l[i] = do_something_with_item(item)

or

new_l = []
for item in l:
    new_l.append(do_something(item))
l = new_l

There are innumerable variations of this scheme. 

Diez



More information about the Python-list mailing list