question on slices
John Baxter
jwbaxter at spamcop.net
Tue Mar 26 22:45:34 EST 2002
In article <rj7v9ug37qguulsuocutqr5mfdh9p4c8ee at 4ax.com>,
John Warney <john at yahoo.com> wrote:
> I am sorta new to programming, i have had an intro to programming
> using C++ and thats it. Other than that i have kinda read a few
> things but now i am into Python.....blah blah blah.....
> The issue that i have a problem with is slices. for instance let me
> show you a snippet:
>
> >>> numlist=[0, 1, 2, 3]
> >>> numlist[1]
> 1
> >>> numlist[2]
> 2
> >>> numlist[1:2]
> [1]
>
> This last one doesnt make since to me since i am asking for a range
> from 1-2. Why in the world does it give me 1 when i am asking for 1-2
> which would logically be:
>
> >>> numlist[1:2]
> [1, 2]
>
> but it's not. it doesnt make since. Just seems strange when i just
> was in a C++ class and it would do the logical thing.
You think you are asking for the elements from 1 *through* 2.
You aren't...instead, you are asking for the elements from 1 through
just before 2. Before you say how clearly bogus that is, play around
with slices given the above and note how consistently they work,
particularly with negative (counting from the ends) numbers given.
Also, note that
numlist=[0, 1, 2, 3]
otherlist = numlist[0:2] + numlist[2:]
print otherlist
makes sense...ie, otherlist looks the same as numlist. No need to fudge
with a +1 or a -1 to make that happen.
--john
More information about the Python-list
mailing list