lists and append, and loop iteration

ivnowa at hvision.nl ivnowa at hvision.nl
Wed Sep 22 04:44:28 EDT 1999


On 22 Sep 99, at 17:32, Mark Krischer 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?
> 
> 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)
> 
> 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]

I don't think the dict can "see" the append... what you're doing is 
trying to get a value from a dict, then doing something with that 
value. So essentially it's two steps:

a = dict['new_key']
a.append(new_value)

even though you can write them as one step with 
dict['new_key'].append(new_value). If 'new_key' doesn't exist, 
nothing is returned, so there's nothing to append to.

> am i missing something fundamental that this would completely break?
> 
> 
> 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.

No other way that I know of... you can work around this, by keeping a 
counter, but using range() is better. 


--Hans Nowak (ivnowa at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
Snippets: http://tor.dhs.org/~zephyrfalcon/snippets/




More information about the Python-list mailing list