lists and append, and loop iteration

Mark Krischer mkrisch at radiata.com
Wed Sep 22 03:32:27 EDT 1999


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]

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.

thoughts?

thanks in advance.

--mk




More information about the Python-list mailing list