A couple questions

Jeff Shannon jeff at ccvcorp.com
Wed May 15 15:15:57 EDT 2002


In article <5735eug1qqu1mn38s16svempcff7obqp7t at 4ax.com>, Gonçalo 
Rodrigues says...
> Hi, just a couple a questions,
> 
> 1. If I have a class as in
> 
> class Somesuch(object):
>     <whatever>
> 
> in the __init__ method should I/must I call object.__init__? I am asking
> this because in GvR's descintro, the object cass __init__ method is said
> to be a no-op (it does nothing).

If it's a no-op, then it makes no difference whether you call it 
or not.  No need to bother with it.

 
> 2. What is the pythonic way to traverse a list while modifying it? Put
> in another way, is
> 
> for i in range(len(mylist)):
>     <change mylist here>
> 
> safe or am I bound to use a while loop with an explicit counter?

It is probably *not* safe if you are adding to / removing from 
mylist.  If you're modifying values inplace, but not changing the 
length/ordering of the list, you should be okay.  Thus,

mylist = ['1', '2', '3']
for I in range(len(mylist)):
    mylist[I] = int(mylist[I])

is safe, though better done as a map/listcomp --

mylist = [int(a) for a in mylist]
mylist = map(int, mylist)

But

mylist = [0, 0, 1, 2]
for I in range(len(mylist)):
    a = mylist[I]
    if not a:
        mylist.remove(a)

is not safe.  The unsafeness has nothing to do with explicit 
integer indexing, either -- it's just as unsafe to do

for a in mylist:
   if not a:
      mylist.remove(a)

I'd usually do this sort of thing with a listcomp or with 
map/filter, but if you must use a for loop, then you can iterate 
over a copy of the list:

for a in mylist[:]:
    if not a:
        mylist.remove(a)

Equivalent versions:

mylist = [a for a in mylist if a]
mylist = filter(None, mylist)

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list