473,770 Members | 2,273 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 #1
54 3979
>>>>> "seberino@spawa r" == seberino@spawar navy mil <se******@spawa r.navy.mil> writes:
Many people I know ask why Python does slicing the way it does.....
Can anyone /please/ give me a good defense/justification?? ?


Try http://www.everything2.com/index.pl?node_id=1409551

Ganesan

--
Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA
Web: http://employees.org/~rganesan | http://rganesan.blogspot.com

Jul 19 '05 #2
<se******@spawa r.navy.mil>
Many people I know ask why Python does slicing the way it does.....


Half open intervals are just one way of doing things. Each approach has its own
merits and issues.

Python's way has some useful properties:

* s == s[:i] + s[i:]

* len(s[i:j]) == j-i # if s is long enough
OTOH, it has some aspects that bite:

* It is awkward with negative strides such as with s[4:2:-1]. This was the
principal reason for introducing the reversed() function.

* It makes some people cringe when they first see it (you're obviously in that
group).
I suspect that whether it feels natural depends on your previous background and
whether you're working in an environment with arrays indexed from one or from
zero. For instance, C programmers are used to seeing code like: for(i=0 ;
i<n; i++) a[i]=f(i); In contrast, a BASIC programmer may be used to FOR I = 1
to N: a[i]=f(I); NEXT. Hence, the C coders may find Python's a[:n] to be
more natural than BASIC programmers.

As long as a language is consistent about its approach, you just get used to it
and it stops being an issue after a few days.
Raymond Hettinger
Jul 19 '05 #3
Raymond Hettinger wrote:
to seeing code like: for(i=0 ; i<n; i++) a[i]=f(i); In contrast, a
BASIC programmer may be used to FOR I = 1 to N: a[i]=f(I); NEXT.


Afaik, at least BBC BASIC uses zero based arrays :-) Maybe ZX Spectrum
Basic too (too long ago to remember).

--
John MexIT: http://johnbokma.com/mexit/
personal page: http://johnbokma.com/
Experienced programmer available: http://castleamber.com/
Happy Customers: http://castleamber.com/testimonials.html
Jul 19 '05 #4
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.

Given another slice like mystring[2:4], you know instantly by
looking at the slice indices that this contains 4-2 = 2 characters
from the original string. If the last index were included in the
slice, you'd have to remember to add 1 to get the number of
characters in the sliced string.

It all makes perfect sense when you look at it this way!
Nick
Jul 19 '05 #5
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.

But most programmers are used to do it the Python (and most other
languages) way, so this opportunity has been missed for good.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #6
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.

--
Antoon Pardon
Jul 19 '05 #7
On Wednesday 20 April 2005 01:36 am, Raymond Hettinger wrote:
<se******@spawa r.navy.mil>
Many people I know ask why Python does slicing the way it does.....
[...] Python's way has some useful properties: [...] OTOH, it has some aspects that bite: [...] I suspect that whether it feels natural depends on your previous background and
whether you're working in an environment with arrays indexed from one or from
zero. For instance, C programmers are used to seeing code like: for(i=0 ;
i<n; i++) a[i]=f(i); In contrast, a BASIC programmer may be used to FOR I = 1
to N: a[i]=f(I); NEXT. Hence, the C coders may find Python's a[:n] to be
more natural than BASIC programmers.


Well, I learned Basic, Fortran, C, Python --- more or less. And I first found
Python's syntax confusing as it didn't follow the same rules as any of the
previous ones.

However, I used to make "off by one" errors all the time in both C and Fortran,
whereas I hardly ever make them in Python.

So I like Python's slicing because it "bites *less*" than intervals in C or Fortran.

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

Jul 19 '05 #8
Raymond Hettinger <py****@rcn.com > wrote:
<se******@spaw ar.navy.mil>
Many people I know ask why Python does slicing the way it does.....

Python's way has some useful properties:

* s == s[:i] + s[i:]

* len(s[i:j]) == j-i # if s is long enough


The latter being particularly helpful when i = 0 -- the first n
elements are s[:n] . (Similarly elegantly, although of no
practical significance, s == s[0:len(s)] .)

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jul 19 '05 #9
Hallöchen!

Antoon Pardon <ap*****@forel. vub.ac.be> writes:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik .rwth-aachen.de>:
[...]

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.


In HTBasic you have the choice between 0 and 1; there is a global
source code directive for it. However, hardly anybody really wants
to use HTBasic.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jul 19 '05 #10

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
3547
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
2053
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
4383
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
2757
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
6024
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
9619
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
9454
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,...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6712
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
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.