[Tutor] Two questions
Lloyd Kvam
pythontutor@venix.com
Sat, 13 Apr 2002 12:42:43 -0400
That will teach me to post without checking!
The list assignment does not let you assign beyond the existing
size of a list. It prevents:
alist = []
alist[5] = 'hi'
What should Python do about the missing elements before [5]?
This works:
alist = [1,2,3,4,5,6]
alist[5] = 'hi'
because the slot 5 has been created. (slot 5 == the sixth element)
Yes, Andrei's and Lloyd Allen's later posts cover this better...
Erik Price wrote:
>
> On Saturday, April 13, 2002, at 10:04 AM, Lloyd Kvam wrote:
>
>> You need to create a (possibly empty) list before you can stick
>> something into the list.
>
>
> I thought that, being a dynamically typed language, you could just
> create list elements on the fly (in the way that henry steigerwaldt did
> in his original script). I know/have heard that it's good practice to
> declare a variable first, like
>
> site_url = []
>
> but I thought that it was possible to just jump in and start assigning
> directly to elements in a list. I can't -- even if I declare site_url
> as a list, the following doesn't work:
>
> >>> site_url=[]
> >>> site_url[0] = 'hi'
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> IndexError: list assignment index out of range
>
> Why is that? I thought dynamic typing was more flexible than this... ?
>
>> i = 0
>> site_url = [] # create an empty list
>> site_url[i] = fileobject.readline()
>> print "site_url = ", site_url[i]
>>
>> It is usually simpler to not track the positions when putting
>> things into the list. Something like:
>>
>> site_url = []
>> site_url.append( fileobject.readline())
>>
>> simply adds the url to the end of the list. You can NOT add
>> things to a tuple. A tuple can NOT be changed. If you want your
>> URLs to be in a tuple, create the list first. Then use the
>> builtin tuple function.
>
>
> Then how come I can do:
>
> tuple1 = (1, 2)
> tuple2 = (3, 4)
> tuple3 = tuple1 + tuple2
> (1, 2, 3, 4)
>
> or is that because I'm creating a new tuple?
>
> Erik
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582