473,804 Members | 3,277 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why are slice indices the way they are in python?

A couple of off the wall questions.

It seems to me that there is usually a solid *reason* for things in
Python and I'm wondering about the rationale for the way slicing works:

my_string[2:5]

gets you the 3rd through the 3rd through the 5th character of the
string because indexing starts at 0 and you get everything up to, but
not including the second index.

Why? It doesn't seem intuitive to me. To me, it makes it harder, not
easier, to work with slices than if indexing started at 1 and the
above expression got you the 2nd throught the 5th character.

Another thing that I've been puzzling over is the pow() function.

pow(x,y) gives x**y. Fine.

But pow(x,y,z) gives (x**y) % c

I'm curious to know what the pressing reason for such a feature was.

Nov 30 '06 #1
5 1703

"Steve Bergman" <st***@rueb.com wrote in message
news:11******** **************@ 14g2000cws.goog legroups.com...
>A couple of off the wall questions.

It seems to me that there is usually a solid *reason* for things in
Python and I'm wondering about the rationale for the way slicing works
Yes, see below.
my_string[2:5]

gets you the 3rd through the 3rd through the 5th character of the
string because indexing starts at 0 and you get everything up to, but
not including the second index.

Why?
len(s[2:5])== 5-2
s[2:5] + s[5:7] == s[2:7]

Another thing that I've been puzzling over is the pow() function.

pow(x,y) gives x**y. Fine.

But pow(x,y,z) gives (x**y) % c
you obvious meant (x**y) % z
>
I'm curious to know what the pressing reason for such a feature was.
Such exponential remainders are used in cryptography work, for instance,
with fairly large values, and can be efficiently computed, especially in C,
*without* computing a humongous x**y intermediate value.

Since this is an int function, it does not really belong in the floating
point math module.

Terry Jan Reedy

Nov 30 '06 #2
Ant

Steve Bergman wrote:

....
Why? It doesn't seem intuitive to me. To me, it makes it harder, not
easier, to work with slices than if indexing started at 1 and the
above expression got you the 2nd throught the 5th character.
Dijkstra has an article about this:
http://www.cs.utexas.edu/users/EWD/t...xx/EWD831.html

In practice it probably wouldn't make a great deal of difference. Here
at my current job, we have a situation where a bunch of Progress 4GL
programmers have been taught Java and let loose on the code base. we
now have a situation where there are a plethora of methods written
designed to be 1-based, and you have to trawl through the code to work
out if the method was written by a Java programmer or a 4GL programmer
to save on array index exceptions...

The infuriating thing is that if you are iterating over an array in
Java, and have to use one of the functions based on an array index, you
have to use function(i + 1). Drilling back through the code, and
invariably you have the function written:

def function(i):
return array[i-1]

!!! (at least you would if the Java was written in Python by 4GL
programmers, but you get the idea ;-) )

Nov 30 '06 #3
Why? It doesn't seem intuitive to me. To me, it makes it harder, not
easier, to work with slices than if indexing started at 1 and the
above expression got you the 2nd throught the 5th character.
Zero-based indices and excluding last index often works nicer, it is
not the rule, but all my experience says that.

a[i:i] is very handy to have in many algorithms, so you don't have to
exclude this case explicitly.
Index starting at 1 or including N often adds +-1 expressions to the
code. I think that http://en.wikipedia.org/wiki/Modular_arithmetic
makes it more intuitive.

And if talking about dates, then I suggest NEVER use 2006-12-31
23:59:59 in data, always 2007-01-01 00:00:00 instead. If customer wants
to see former on the screen just substruct 1 millisecond from the data
and round it to what is needed. It makes all arithmetics, finding
period collapses, time differences, etc much more painless. You
sometimes don't even know if your database supports seconds,
milliseconds, microseconds and what your operating system and
programming language support. So if you are using inclusive end date
you may find yourself in trouble very soon.

Again, its not intuitive for ordinary people, but math people and
programmers often find 0-based and exlusive ends are nicer to work
with, at least me :)
Another thing that I've been puzzling over is the pow() function.

pow(x,y) gives x**y. Fine.

But pow(x,y,z) gives (x**y) % c

I'm curious to know what the pressing reason for such a feature was.
This makes cryptography code 100 times faster.

Oleg

Nov 30 '06 #4
On Thu, 2006-11-30 at 08:58 -0800, og****@gmail.co m wrote:
And if talking about dates, then I suggest NEVER use 2006-12-31
23:59:59 in data, always 2007-01-01 00:00:00 instead.
Forgive me for my ignorance, but isn't "2006-12-31 23:59:59" actually
one entire second earlier than "2007-01-01 00:00:00"? Hence they are
two different dates are they not?

Michael
Dec 1 '06 #5
Michael Torrie wrote:
Forgive me for my ignorance, but isn't "2006-12-31 23:59:59" actually
one entire second earlier than "2007-01-01 00:00:00"? Hence they are
two different dates are they not?
given the context, maybe the poster meant that he's storing date
*ranges* as [start, stop) (i.e. including start but not including
stop).

</F>

Dec 1 '06 #6

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

Similar topics

15
2495
by: Roberto A. F. De Almeida | last post by:
I found that when using negative indices, the slice object passed to __getitem__ depends on the number of slices. An example to clarify: class a: def __getitem__(self, index): return index >>> b = a() >>> print b Traceback (most recent call last):
2
1768
by: Uwe Mayer | last post by:
Hi, a class of mine should support the list interface and implements the __len__ and __getitem__ methods. Now when I ask for an unbounded slice: >>> len( myObj ) my __getitem__(self, y) method gets called with
1
3794
by: Steven Bethard | last post by:
Is there a reason that itertools.islice doesn't support None arguments for start and step? This would be handy for use with slice objects: >>> r = range(20) >>> s1 = slice(2, 10, 2) >>> s2 = slice(2, 10) >>> s3 = slice(10) >>> list(itertools.islice(r, s1.start, s1.stop, s1.step)) >>> list(itertools.islice(r, s2.start, s2.stop, s2.step))
108
6476
by: Bryan Olson | last post by:
The Python slice type has one method 'indices', and reportedly: This method takes a single integer argument /length/ and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the /start/ and /stop/ indices and the /step/ or stride length of the slice. Missing or out-of-bounds indices are handled in a manner...
40
2624
by: Ron Adam | last post by:
After considering several alternatives and trying out a few ideas with a modified list object Bengt Richter posted, (Thank You), I think I've found a way to make slice operation (especially far end indexing) symmetrical and more consistent. So to find out if this is indeed a possibility, it would be nice to get a few opinions at this point. So blast away... or hopefully tell me what you like about it instead. ;-) (Any suggestions or...
1
1531
by: 700MHz | last post by:
I cannot quite understand when the third index is a negative number,like this: a = '0123456789' a I know the index step is 2, so it will collect items from offset 1, 3, 5, 7, 9 but when a negative number come,like: a answer '10', and a only answer '', what is the different between the two expression, where does the offset begin and what is the end offset?
7
2220
by: Alexandre Guimond | last post by:
Hi all, i'm trying to deepcopy a slice object but i get the following error. Does anyone know a workaround? ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) on win32 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last):
2
7256
by: smichr | last post by:
It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that...
3
2993
by: Bas | last post by:
Hi, stupid question, but would it be possible to somehow merge xrange (which is supposed to replace range in py3k) and slice? Both have very similar start, stop and step arguments and both are lightweight objects to indicate a range. But you can't do a and 'for i in slice(10,20)'. The only difference is see is some behavior with infinities (e.g. object gives a slice(3,maxint) inside _getitem_ , but I think this should not be a large...
2
3894
by: ajcppmod | last post by:
I'm really confused about results of slices with negative strides. For example I would have then thought of the contents of mystr as: indices 0 1 2 3 4 5 6 7 8 content m y s t r i n g with mystr = 'my '
0
9708
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
10588
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
10340
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...
1
10324
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
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7623
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
5527
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
4302
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
3827
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.