[Tutor] list initialization question
Blake Winton
bwinton@tor.dhs.org
Mon, 3 Apr 2000 09:53:10 -0400
* Tim Condit <timc@ans.net> [000403 09:38]:
> Why does this fail...
>
> >>> x = []
> ... x[i] = whrandom.randint(1, 100)
> IndexError: list assignment index out of range
>
> ... but this succeeds?
> >>> x = range(11)
> ... x[i] = whrandom.randint(1, 100)
>
> Is it necessary to not only initialize a list, but also to populate it? Or
Exactly. Well, sort of exactly. The line "x=[]" says that x is a list,
but it doesn't tell it how long it is. Well, it actually tells it that
it's a list of length 0, so any index is out of the valid range.
(As well, what do you expect the list to contain if you specify a
length, but no data? I can guarantee that someone else expects
something different, so in the spirit of Fewest Surprises, Python has
decided to not let you do that. ;)
For a Java-esque workaround try this instead:
>>> x = [None]*10
>>> x
[None, None, None, None, None, None, None, None, None, None]
>>> x[1] = 3
>>> x
[None, 3, None, None, None, None, None, None, None, None]
Later,
Blake.
--
9:44am up 5 days, 10:18, 2 users, load average: 0.54, 0.11, 0.04