Jumping around when assigning elements

Paul Rubin http
Tue Dec 16 09:54:02 CET 2003


matt at killermookie.org (Matthew Sims) writes:
> For lists, I understand this:
> C=["need","some","help"]
> print C[1]
> some
> 
> But I can't seem to do this:
> C[3]="here"
> 
> I know about C.append("here") but this brings me to my question...
> 
> Is there anyway to assign to an element that wasn't defined in the
> beginning? Like if I wanted element 5 assigned but not element 4
> without using "" or None?

The simplest way is with a dictionary instead of a list:

D = {0:"need", 1:"some", 2:"help"}
print D[1]
some

Then you can do

D[3] = "here"
D[97] = "way over there"
D["banana"] = "yellow"

etc.




More information about the Python-list mailing list