[Tutor] (no subject)
Daniel Yoo
dyoo@hkn.EECS.Berkeley.EDU
Wed, 30 Aug 2000 19:19:51 -0700 (PDT)
> 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?
When you try something like:
a[0:2]
this will take a[0] and a[1]. It's a little weird at first, but it
actually simplifies program logic that works with arrays. You'll need to
write a few programs, though, before it makes sense.
The '[]' operator will make a slice starting at the left element, all the
way up to, but not including, the right element.
Oh, also,
a[:2]
is the same thing as a[0:2], and can be read as "take the first 2 elements
of 'a'".
If you're curious, the range() function has similar behavior:
###
>>> range(0)
[]
>>> range(1)
[0]
>>> range(2)
[0, 1]
###