[Tutor] (no subject)
amoreira@mercury.ubi.pt
amoreira@mercury.ubi.pt
Thu, 31 Aug 2000 09:56:22 +0100
deng wei wrote:
>
> Hi:
> Here is a question in the python munual 3.1.3.
> The example said:
> a = ['spam', 'eggs', 100, 1234];
> a[0]='spam',a[1]='eggs',a[2]=100 and a[4]=1234;
> It then said:
> a[0:2]=[1,12]
> I think it's a error assignment.
> 'Cause I believe a[0:2]=['spam','eggs',100];
> Why?
> Any comments are Welcome.Thanks in advance.
Hello!
No, that's not the way slices go. before the second assignment, a[0:2]
is ['spam','eggs'], not, as you say, ['spam','eggs',100]. In general,
list[n1:n2] returns the slice of list that starts at position n1 (first
position in the list is #0) and ends *just before* n2. So when you say
a[0:2]=[1,12] you are saying that you wnat the first two elements of a
be assigned numbers 1 and 12.
Check it out with examples:
>>> a=['spam','eggs',100,1234]
>>> a[0:2]
['spam', 'eggs']
>>> a[0:1]
['spam']
>>> a[0]
'spam'
Oh, just another thing: the semi-colons ';' at the end of a line are
unnecessary. You just need them to separate different instructions set
in the same line.
Hope it helped
Cheers,
Ze