[Tutor] List weirdness
Alan Gauld
alan.gauld at btinternet.com
Fri Feb 13 09:47:06 CET 2009
"Moos Heintzen" <iwasroot at gmail.com> wrote
> >>> d = [[]]
> >>> d[0][0]=1
> IndexError: list assignment index out of range
> >>> d[0].append(1)
> >>> d
> [[1]]
>
> I guess I can't reference [0] on an empty list.
Thats right. You can't assign a value to a position in
a list that hasn't been created yet. It has nothing to
do with nesting, its the same for a simople lust:
>>> lst = []
>>> lst[0] = 66
Traceback (most recent call last):
File "<input>", line 1, in <module>
IndexError: list assignment index out of range
>>> lst.append(66)
>>> lst
[66]
You can also use insert, which takes an index.
But if the index is non existent it appends...
>>> lst2 = []
>>> lst2.insert(3,66)
>>> lst2
[66]
>>> lst.insert(3,66)
>>> lst
[66, 66]
>>>
HTH,
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list