Are lists at least as efficient as dictionaries?

Jp Calderone exarkun at intarweb.us
Fri Aug 29 10:54:23 EDT 2003


On Fri, Aug 29, 2003 at 10:07:20AM +0200, Peter Otten wrote:
> Narendra C. Tulpule wrote:
> 
[ snip]
> 
> And now for something completely different:
> 
> >>>> x = ([],)
> >>>> x[0] += ['something']
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > TypeError: object doesn't support item assignment
> 
> += calls the list.__iadd__(self, other) method, which seems to be
> implemented as
> 
> def __iadd__(self, other):
>     self.append(other)
>     return self 

  self.extend(other), actually.  But that's the basic idea, yea.

> 
> The call of this method succeds, but the following assignment fails, because
> tuples are immutable. This could only be remedied if all assignments
> 
> a = a
> 
> were silently ignored, or, if the += operator would not perform an
> assignment, which has the disadvantage that it would no longer work for
> immutables, so that
> >>> i = 1
> >>> i += 1
> >>> print i
> 1 # admittedly faked
> >>>

  += could simply be syntactic sugar for a call to __add__ and then an
assignment.  This would work for mutable and immutable objects.

> 
> You could change __iadd__() to
> 
> def __iadd__(self, other):
>     return self + other
> 
> but then sane behaviour in one special case comes at the cost of always
> creating a copy of a potentially large (say more than 100 items :-) list.

  True, except that list.extend() exists.

  Jp

-- 
"There is no reason for any individual to have a computer in their
home."
                -- Ken Olson, President of DEC, World Future Society
                   Convention, 1977





More information about the Python-list mailing list