473,799 Members | 2,954 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 3989

"James Stroud" <js*****@mbi.uc la.edu> escribió en el mensaje
news:ma******** *************** *************** @python.org...
I like this, it works for any integer.
str="asdfjkl;"
i=-400
print str[:i]+str[i:] asdfjkl; i = 65534214
print str[:i]+str[i:]

asdfjkl;


Actually, this has no relation with the half-open
slices but with the fact that if i goes beyond
the limit of the string then Python, wisely, doesn't
raise an error but instead return the string until
the end. When people say that half-open slices work
for every i, they are tinking in the case i=0.

Javier

_______________ _______________ _______________ ______________
Javier Bezos | TeX y tipografía
jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos
............... ..............| ............... ............... .
CervanTeX (Spanish TUG) | http://www.cervantex.org


Jul 19 '05 #31
On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote:
Terry Hancock wrote:
I used to make "off by one" errors all the time in both C and Fortran,
whereas I hardly ever make them in Python.

Part of the reason may be that most loops over lists involve
iterators,

both endpoints are mentioned explicitly. C++/STL also uses iterators,
but the syntax is repulsive.


That's true of course. It's more likely to show up in manipulating
lists or strings. And Python provides a much richer environment for
processing strings, so one has to deal with explicit indexing much
less.

But I still think that I make fewer error per instance of dealing with
intervals. It's rare that I even have to think about it much when
writing such a thing. Negative indexing also helps a lot.

Terry

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

Jul 19 '05 #32
James Carroll wrote:
If you have five elements, numbered 0,1,2,3,4 and you ask for the
elements starting with the first one, and so on for the length you
would have [0:length]. So [0:5] gives you elemets 0,1,2,3,4. Think
of the weirdess if you had to ask for [0:length-1] to get length
elements... [...] It is a little weired that slicing does [index: count] instead of
[index:index] or [count:count] I agree, but python really does just
flow wonderfully once you see how clean code is that's written [index:
count].


I think you got confused part way through that. Python's
slices are *not* index:count, but are index:index. It's
just that for the example you gave, starting at 0, they
happen to amount to the same thing...

-Peter
Jul 19 '05 #33
"Dan Bishop" <da*****@yahoo. com> writes:
Name a problem space that inherently requires arrays to be 1-based
rather than 0-based.


"inherently " is too strong a word, since after all, we could do all
our computing with Turing machines.

Some algorithms are specified in terms of 1-based arrays. And most
Fortran programs are written in terms of 1-based arrays. So if you
want to implement a 1-based specification in Python, or write Python
code that interoperates with Fortran code, you either need 1-based
arrays in Python or else you need messy conversions all over your
Python code.

The book "Numerical Recipes in C" contains a lot of numerical
subroutines written in C, loosely based on Fortran counterparts from
the original Numerical Recipes book. The C routines are full of messy
conversions from 0-based to 1-based. Ugh.

Again, this (along with nested scopes and various other things) was
all figured out by the Algol-60 designers almost 50 years ago. In
Algol-60 you could just say "integer x(3..20)" and get a 3-based array
(I may have the syntax slightly wrong by now). It was useful and took
care of this problem.
Jul 19 '05 #34
Paul Rubin wrote:
"Dan Bishop" <da*****@yahoo. com> writes:
Name a problem space that inherently requires arrays to be 1-based
rather than 0-based.

"inherently " is too strong a word, since after all, we could do all
our computing with Turing machines.

Some algorithms are specified in terms of 1-based arrays. And most
Fortran programs are written in terms of 1-based arrays. So if you
want to implement a 1-based specification in Python, or write Python
code that interoperates with Fortran code, you either need 1-based
arrays in Python or else you need messy conversions all over your
Python code.


I write Python code that interoperates with Fortran code all the time
(and write Fortran code that interoperates with Python code, too). Very,
very rarely do I have to explicitly do any conversions. They only show
up when a Fortran subroutine requires an index in its argument list.

In Fortran, I do Fortran. In Python, I do Python.

Yes, there is some effort required when translating some code or
pseudo-code that uses 1-based indexing. Having done this a number of
times, I haven't found it to be much of a burden.
The book "Numerical Recipes in C" contains a lot of numerical
subroutines written in C, loosely based on Fortran counterparts from
the original Numerical Recipes book. The C routines are full of messy
conversions from 0-based to 1-based. Ugh.
I contend that if they had decided to just write the C versions as C
instead of C-wishing-it-were-Fortran, they would have made a much better
library. Still sucky, but that's another story.
Again, this (along with nested scopes and various other things) was
all figured out by the Algol-60 designers almost 50 years ago. In
Algol-60 you could just say "integer x(3..20)" and get a 3-based array
(I may have the syntax slightly wrong by now). It was useful and took
care of this problem.


There's nothing that stops you from writing a class that does this. I
believe someone posted such a one to this thread.

I have yet to see a concrete proposal on how to make lists operate like
this.

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 19 '05 #35
Ron
Ron wrote:
se******@spawar .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).
There are actually 4 different ways to slice .... Where s = 'abcd'
With s[i,j]

Foreword slices index, forward steps
a, b, c, d
i= 0, 1, 2, 3
j= 1, 2, 3, 4

s[0,4] = 'abcd'
s[1,3] = 'bc'
.......

Minor correction to this. It's what I get for not realizing how late it
was.

Where s = 'abcd'
With s[i:j:step]

Positive slice index, (+1 step)
a, b, c, d
i= 0, 1, 2, 3
j= 1, 2, 3, 4

s[0:4] = 'abcd'
s[1:3] = 'bc'

Positive slice index, (-1 step)
a, b, c, d
i= 0, 1, 2, 3
j= -5, -4, -3, -2

s[3:-5:-1] = 'dcba'
s[2:-4:-1] = 'cb'

Negative slice index, (+1 step)
a, b, c, d
i= -4, -3, -2, -1
j= 1, 2, 3, 4

s[-4:4] = 'abcd'
s[-3:3] = 'bc'

Reverse slice index, (-1 step)
a, b, c, d
i= -4, -3, -2, -1
j= -5, -4, -3, -2

s[-1:-5:-1] = 'dcba'
s[-2:-4:-1] = 'cb'

Cheers,
Ron_Adam
Jul 19 '05 #36
Antoon Pardon wrote:

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.


Also, everyone, please keep in mind that you always have
the option of using a *dictionary*, in which case your
indices can start wherever you want.

You can't slice them, true, but you can't have
everything. :-)

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #37
Roy Smith wrote:
What would actually be cool is if Python were to support the normal math
notation for open or closed intervals.

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 :-)


Not to mention the sanity of everyone's editors when
they try to do bracket matching!

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #38
be*******@aol.c om wrote:
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]].
But said newbie's expectations will differ considerably
depending on which other language he's coming from. So
he's almost always going to be surprised one way or another.

Python sensibly adopts a convention that long experience
has shown to be practical, rather than trying to imitate
any particular precedent.
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


Who says the Python programmer doesn't have a choice?

class NewbieWarmFuzzy List(list):

def __new__(cls, base, *args):
obj = list.__new__(cl s, *args)
obj.base = base
return obj

def __getitem__(sel f, i):
return list.__getitem_ _(self, i - self.base)

# etc...

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 19 '05 #39
In article <3c************ *@individual.ne t>,
Greg Ewing <gr**@cosc.cant erbury.ac.nz> wrote:
Roy Smith wrote:
What would actually be cool is if Python were to support the normal math
notation for open or closed intervals.
>
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 :-)


Not to mention the sanity of everyone's editors when
they try to do bracket matching!


I have no doubt that somebody could teach emacs python-mode to correctly
match half-open interval brackets.
Jul 19 '05 #40

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

Similar topics

7
2583
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
3551
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
2056
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
4390
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
2760
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
6026
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
9540
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
10475
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
10026
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
7564
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
6805
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
5463
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...
1
4139
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
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.