Jumping around when assigning elements

Shalabh Chaturvedi shalabh at gameboard.org
Mon Dec 15 23:27:39 EST 2003


matt at killermookie.org (Matthew Sims) wrote in message news:<1e963607.0312151408.583221e6 at posting.google.com>...

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

You could try using a dictionary instead of a list. You could even
initialize the dict from the list:

l = ["just", "a", "suggestion"]
d = {}
for k,v in enumerate(l):
    d[k] = v

d[10] = "here"

Of course, to get at the values now, you would need to iterate over
d.values(). Note that you won't necessarily get the values in sorted
order of keys. You would have to do that explicitly if you want.

--
Shalabh




More information about the Python-list mailing list