473,786 Members | 2,445 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why Python does *SLICING* the way it does??

Many people I know ask why Python does slicing the way it does.....

Can anyone /please/ give me a good defense/justification?? ?

I'm referring to why mystring[:4] gives me
elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element).

Many people don't like idea that 5th element is not invited.

(BTW, yes I'm aware of the explanation where slicing
is shown to involve slices _between_ elements. This
doesn't explain why this is *best* way to do it.)

Chris

Jul 19 '05
54 3982
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik .rwth-aachen.de>:
Hallöchen!

nd*@no.spam.org (Nick Efford) writes:
se******@spawar .navy.mil <se******@spawa r.navy.mil> wrote:
Many people I know ask why Python does slicing the way it does.....

Can anyone /please/ give me a good defense/justification?? ?

I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3
but *NOT* mystring[4] (5th element).

mystring[:4] can be read as "the first four characters of
mystring". If it included mystring[4], you'd have to read it as
"the first five characters of mystring", which wouldn't match the
appearance of '4' in the slice.

[...]

It all makes perfect sense when you look at it this way!


Well, also in my experience every variant has its warts. You'll
never avoid the "i+1" or "i-1" expressions in your indices or loops
(or your mind ;).

It's interesting to muse about a language that starts at "1" for all
arrays and strings, as some more or less obsolete languages do. I
think this is more intuitive, since most people (including
mathematicians) start counting at "1". The reason for starting at
"0" is easier memory address calculation, so nothing for really high
level languages.


Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


-1. You can start arrays at 0 or 1 (and arbitrary bases? I don't
recall) in VB, and it's an unmitigated disaster. It adds needless
complexity. What our slicing system loses in elegance in a few cases,
it more than makes up for in consistency throughout all programs.

Peace
Bill Mill
bill.mill at gmail.com
Jul 19 '05 #11
Terry Hancock wrote:

<snip>
So I like Python's slicing because it "bites *less*" than intervals

in C or Fortran.

I disagree. Programming languages should not needlessly surprise
people, and a newbie to Python probably expects that x[1:3] =
[x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95,
Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention,
and I don't know of Fortran or R programmers who complain (don't follow
Matlab enough to say). There are Python programmers, such as the OP and
me, who don't like the Python convention. What languages besides Python
use the Python slicing convention?

Along the same lines, I think the REQUIREMENT that x[0] rather than
x[1] be the first element of list x is a mistake. At least the
programmer should have a choice, as in Fortran or VBA. In C starting at
0 may be justified because of the connection between array subscripting
and pointer arithmetic, but Python is a higher-level language where
such considerations are less relevant.

Jul 19 '05 #12
Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


Argggh. Having two (or more!) ways to do it, would mean that every time I
read somebody else's code, I would have to figure out which flavor they are
using before I could understand what their code meant. That would be evil.

What would actually be cool is if Python were to support the normal math
notation for open or closed intervals. Any of the following would make
sense:

foo = bar (1, 2)
foo = bar (1, 2]
foo = bar [1, 2)
foo = bar [1, 2]

That would certainly solve this particular problem, but the cost to the
rest of the language syntax would be rather high :-)
Jul 19 '05 #13
Op 2005-04-20, Bill Mill schreef <bi*******@gmai l.com>:
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik .rwth-aachen.de>:
> Hallöchen!
>
> nd*@no.spam.org (Nick Efford) writes:
>
>> se******@spawar .navy.mil <se******@spawa r.navy.mil> wrote:
>>> Many people I know ask why Python does slicing the way it does.....
>>
>>> Can anyone /please/ give me a good defense/justification?? ?
>>
>>> I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3
>>> but *NOT* mystring[4] (5th element).
>>
>> mystring[:4] can be read as "the first four characters of
>> mystring". If it included mystring[4], you'd have to read it as
>> "the first five characters of mystring", which wouldn't match the
>> appearance of '4' in the slice.
>>
>> [...]
>>
>> It all makes perfect sense when you look at it this way!
>
> Well, also in my experience every variant has its warts. You'll
> never avoid the "i+1" or "i-1" expressions in your indices or loops
> (or your mind ;).
>
> It's interesting to muse about a language that starts at "1" for all
> arrays and strings, as some more or less obsolete languages do. I
> think this is more intuitive, since most people (including
> mathematicians) start counting at "1". The reason for starting at
> "0" is easier memory address calculation, so nothing for really high
> level languages.
Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


-1. You can start arrays at 0 or 1 (and arbitrary bases? I don't
recall) in VB, and it's an unmitigated disaster. It adds needless
complexity.


Complexity that is now put on the programmers shoulders.

If I have a table with indexes going from -13 to +7, I have to
add the offset myself if I want to use a list for that.
What our slicing system loses in elegance in a few cases,
it more than makes up for in consistency throughout all programs.


You write this af if other solutions can't be consistent.

--
Antoon Pardon
Jul 19 '05 #14
Op 2005-04-20, Roy Smith schreef <ro*@panix.com> :
Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


Argggh. Having two (or more!) ways to do it, would mean that every time I
read somebody else's code, I would have to figure out which flavor they are
using before I could understand what their code meant. That would be evil.


This is nonsens. table[i] = j, just associates value j with key i.
That is the same independend from whether the keys can start from
0 or some other value. Do you also consider it more ways because
the keys can end in different values?

--
Antoon Pardon
Jul 19 '05 #15
On 20 Apr 2005 13:39:42 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-04-20, Bill Mill schreef <bi*******@gmai l.com>:
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik .rwth-aachen.de>:
> Hallöchen!
>
> nd*@no.spam.org (Nick Efford) writes:
>
>> se******@spawar .navy.mil <se******@spawa r.navy.mil> wrote:
>>> Many people I know ask why Python does slicing the way it does......
>>
>>> Can anyone /please/ give me a good defense/justification?? ?
>>
>>> I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3
>>> but *NOT* mystring[4] (5th element).
>>
>> mystring[:4] can be read as "the first four characters of
>> mystring". If it included mystring[4], you'd have to read it as
>> "the first five characters of mystring", which wouldn't match the
>> appearance of '4' in the slice.
>>
>> [...]
>>
>> It all makes perfect sense when you look at it this way!
>
> Well, also in my experience every variant has its warts. You'll
> never avoid the "i+1" or "i-1" expressions in your indices or loops
> (or your mind ;).
>
> It's interesting to muse about a language that starts at "1" for all
> arrays and strings, as some more or less obsolete languages do. I
> think this is more intuitive, since most people (including
> mathematicians) start counting at "1". The reason for starting at
> "0" is easier memory address calculation, so nothing for really high
> level languages.

Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


-1. You can start arrays at 0 or 1 (and arbitrary bases? I don't
recall) in VB, and it's an unmitigated disaster. It adds needless
complexity.


Complexity that is now put on the programmers shoulders.

If I have a table with indexes going from -13 to +7, I have to
add the offset myself if I want to use a list for that.
What our slicing system loses in elegance in a few cases,
it more than makes up for in consistency throughout all programs.


You write this af if other solutions can't be consistent.


Propose one, and I won't write it off without thinking, but my bias is
way against it from experience. Knowledge gets scattered across the
program, unless you're defining the start index every time you use the
list, which seems no better than adding an offset to me.

Peace
Bill Mill
bill.mill at gmail.com
Jul 19 '05 #16
> Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.

Subclass from builtin list - and make the necessary adjustmenst yourself in
an overloaded __getitem__.

--
Regards,

Diez B. Roggisch
Jul 19 '05 #17
Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Op 2005-04-20, Roy Smith schreef <ro*@panix.com> :
Antoon Pardon <ap*****@forel. vub.ac.be> wrote:
Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


Argggh. Having two (or more!) ways to do it, would mean that every time I
read somebody else's code, I would have to figure out which flavor they are
using before I could understand what their code meant. That would be evil.


This is nonsens. table[i] = j, just associates value j with key i.
That is the same independend from whether the keys can start from
0 or some other value. Do you also consider it more ways because
the keys can end in different values?


There are certainly many examples where the specific value of the
first key makes no difference. A good example would be

for element in myList:
print element

On the other hand, what output does

myList = ["spam", "eggs", "bacon"]
print myList[1]

produce? In a language where some lists start with 0 and some start
with 1, I don't have enough information just by looking at the above
code.
Jul 19 '05 #18
On Wednesday 20 April 2005 07:52 am, Antoon Pardon wrote:
Personnaly I would like to have the choice. Sometimes I prefer to
start at 0, sometimes at 1 and other times at -13 or +7.


Although I would classify that as a "rare use case". So, it "ought
to be possible to do it, but not necessarily easy". Which
Python obliges you on --- you can easily create a relocatable list
class that indexes and slices anyway you see fit, e.g.:
class reloc(list): .... def __init__(self, start, contents=()):
.... self.start = start
.... for item in contents:
.... self.append(ite m)
.... def __getitem__(sel f, index):
.... if isinstance(inde x, slice):
.... if (not (self.start <= index.start < self.start + len(self)) or
.... not (self.start <= index.stop < self.start + len(self))):
.... raise IndexError
.... return self.__class__. __base__.__geti tem__(self, slice(index.sta rt-self.start, index.stop-self.start, index.step))
.... else:
.... if not (self.start <= index < self.start + len(self)):
.... raise IndexError
.... return self.__class__. __base__.__geti tem__(self, index - self.start)
....
....
r = reloc(-13, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'])
r[0] 'n' r[-12] 'b' r[-13] 'a' r[-14] Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 14, in __getitem__
IndexError r[0] 'n' r[3] 'q' r[4] Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 14, in __getitem__
IndexError


Note that I added the IndexError to avoid the bizarre results you
get due to "negative indexing" in the list base class (now they
would change behavior at -13 instead of at 0, which is counter-
intuitive to say the least). Better to cry foul if an index out of
range is called for in this case, because it's gotta be a bug.

What do you think, should I send it to Useless Python? ;-)

Cheers,
Terry

--
Terry Hancock ( hancock at anansispacework s.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #19
Torsten Bronger <br*****@physik .rwth-aachen.de> writes:
It's interesting to muse about a language that starts at "1" for all
arrays and strings, as some more or less obsolete languages do. I
think this is more intuitive, since most people (including
mathematicians) start counting at "1". The reason for starting at
"0" is easier memory address calculation, so nothing for really high
level languages.


There are very good reasons for half-open intervals and starting at 0
apart from memory organization. Dijkstra explained this quite well in
http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF

Bernhard

--
Intevation GmbH http://intevation.de/
Skencil http://skencil.org/
Thuban http://thuban.intevation.org/
Jul 19 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2582
by: Christian Neumann | last post by:
Hello, i have a problem with the built-in function xrange(). Could you by any chance be able to help? I use Python 2.3.4 (final) and i think there is a bug in the built-in
17
3549
by: Just | last post by:
While googling for a non-linear equation solver, I found Math::Polynomial::Solve in CPAN. It seems a great little module, except it's not Python... I'm especially looking for its poly_root() functionality (which solves arbitrary polynomials). Does anyone know of a Python module/package that implements that? Just
11
2055
by: jbperez808 | last post by:
>>> rs='AUGCUAGACGUGGAGUAG' >>> rs='GAG' Traceback (most recent call last): File "<pyshell#119>", line 1, in ? rs='GAG' TypeError: object doesn't support slice assignment You can't assign to a section of a sliced string in Python 2.3 and there doesn't seem to be mention of this as a Python 2.4 feature (don't have time to actually try
53
4387
by: Michael Tobis | last post by:
Someone asked me to write a brief essay regarding the value-add proposition for Python in the Fortran community. Slightly modified to remove a few climatology-related specifics, here it is. I would welcome comments and corrections, and would be happy to contribute some version of this to the Python website if it is of interest. ===
18
2758
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning from the experts. I feel there's a tradeoff between clear, easily readdable and extensible code on one side, and safe code providing early errors and useful tracebacks on the other. I want both! How do you guys do it? What's the pythonic way? Are...
12
6025
by: kath | last post by:
How do I read an Excel file in Python? I have found a package to read excel file, which can be used on any platform. http://www.lexicon.net/sjmachin/xlrd.htm I installed and working on the examples, I found its printing of cell's contents in a different manner. print sh.row(rx)
0
222
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 420 open ( +6) / 3510 closed (+12) / 3930 total (+18) Bugs : 944 open ( -5) / 6391 closed (+15) / 7335 total (+10) RFE : 249 open ( +2) / 245 closed ( +0) / 494 total ( +2) New / Reopened Patches ______________________
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9492
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10360
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9960
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.