lists and append, and loop iteration

Fredrik Lundh fredrik at pythonware.com
Wed Sep 22 04:04:56 EDT 1999


Mark Krischer <mkrisch at radiata.com> wrote:
> this might be a newbie a question, but is there a reason why append
> doesn't create a list if the list doesn't exist?

catch 22: if you don't have a list, you cannot figure
out what "append" means.  it's a method of the list
type, you know...

> it seems to add a bit of complexity to have to do something like:
> 
> dict = {}
> 
> if 'new_key' not in dict.keys():
> dict['new_key'] = [new_value]
> else:
> dict['new_key'].append(new_value)

ouch.  that "key no in dict.keys" hurts my eyes ;-)

here are a few ways to do what you want. if you
want best performance, you have to do some bench-
marks on your data.

list = dict.get(key)
if list is None:
    list = dict[key] = []
list.append(value)

try:
    dict[key].append(value)
except KeyError:
    dict[key] = [value]

if dict.has_key(key):
    dict[key].append(value)
else:
    dict[key] = [value]

or you could of course roll your own dictionary
type:

import UserDict

class myDict(UserDict.UserDict):
    def __getitem__(self, key):
 try:
     return self.data[key]
 except KeyError:
     list = []
     self.data[key] = list
     return list
    
dict = myDict()

dict[key].append(value)

> it seems like i should just be able to say "list.append(new_value)"
> and if list doesn't exist, 

but if list doesn't exist, how can you refer to it?
how do you expect Python to figure out what
object "append" belongs to?

> and while i'm bending your ear, let me ask a second question.
> 
> if i do:
> for element in list:
> do something with element
> 
> is there any to find out what my current index is? i've basically been
> doing something like:
> list.index(element)
> 
> this happens to work fine for what i'm doing now, but only because i
> don't care about doubles in the list, but should that ever be a problem,
> how will i know which element i'm dealing with.
> 
> i figure i can always do:
> for i in range(len(list)):
> do something with list[i]
> 
> but it just feels like i should be able to things the other way as well.

you cannot.  there have been a few proposals to change the
syntax so you can get at the internal loop counter, but nothing
has yet made it into the language.

</F>





More information about the Python-list mailing list