lists and append, and loop iteration

Charles G Waldman cgw at fnal.gov
Wed Sep 22 05:22:08 EDT 1999


Mark Krischer writes:
 > 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?
 > 
 > 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)
 > 

I would write 

 dict['new_key'] = dict.get('new_key',[]) + [new_value]

 > it seems like i should just be able to say "list.append(new_value)" and
 > if list doesn't exist, 
 > i get "list[0] = [new_value]
 > 
 > am i missing something fundamental that this would completely break?

It doesn't make any sense that a method invocation on a nonexistent
object should cause that object to spring into existence!  When you
say "object.method(arg)" the first thing (Guido and Tim will probably
correct me here) that Python does is to look up object and look for a
method definition called "method".  Keep in mind, when you write
"list.append(new_value)", despite the descriptive name, "list" may not
be a list object, it could be an object of any class which has an
"append" method defined.  How is Python to know that in this context
it should create a list?

 > 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.


 for i in range(len(list)):
     element = list[i]

Also note that it's not really a great idea to call your lists "list"
because that makes it akward if you want to call the built-in function
of the same name.




More information about the Python-list mailing list