[Tutor] list initialization question

alan.gauld@bt.com alan.gauld@bt.com
Mon, 3 Apr 2000 17:28:12 +0100


> Why does this fail...
> 
> >>> x = []

Here you create an empty list - ie. no members

> >>> for i in range(11):
> ...      x[i] = whrandom.randint(1, 100)

here you try to access the ith element of x 
- which doesn't exist yet....

Try x.append(....) instead.

> ... but this succeeds? 
> 
> >>> x = range(11)

Here you create a list with 11 members

> >>> for i in range(11):
> ...      x[i] = whrandom.randint(1, 100)

and access one of its members.

> Is it necessary to not only initialize a list, but also to 
> populate it?

Yes, or use append.

Alan G.