473,785 Members | 2,209 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

negative indices for sequence types

dan
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).

This fact is *deeply* buried in the docs, and is not at all intuitive.
One of the big advantages of a high-level language such as Python is
the ability to provide run-time bounds checking on array-type
constructs. To achieve this I will now have to subclass my objects
and add it myself, which seems silly and will add significant
overhead. If you want this behavior, how hard is it to say a = b[x %
len(b)] ??

Can anyone explain why this anomaly exists, and why it should continue
to exist?
Jul 18 '05 #1
8 2154
da*******@yahoo .com (dan) writes:
This fact is *deeply* buried in the docs, and is not at all intuitive.
I find it highly intuitive and very convenient.
If you want this behavior, how hard is it to say a = b[x %
len(b)] ??


*This* I would call un-intuitive. It is also much slower.

To get the last element, you currently write b[-1]. If that was not
available, you would have to write b[len(b)-1], which is still
significantly slower. Also, you might not have a variable name, so try
rewriting foo()[-1].

Regards,
Martin

Jul 18 '05 #2
dan wrote:
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).

This fact is *deeply* buried in the docs, and is not at all intuitive.
One of the big advantages of a high-level language such as Python is
the ability to provide run-time bounds checking on array-type
constructs. To achieve this I will now have to subclass my objects
and add it myself, which seems silly and will add significant
overhead. If you want this behavior, how hard is it to say a = b[x %
len(b)] ??

Can anyone explain why this anomaly exists, and why it should continue
to exist?


After you have recovered from the shock, you probably will admit that
(1) the most common "out of bounds" case is caught:
l = list("abc")
l[3] Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range

and
(2) that accessing elements from the end of the list is something you will
soon appreciate: l[-1] 'c' l[-2:] ['b', 'c']


I think that more code enjoys the beauty of accessing the end of a list than
suffers from uncaught <0 index errors. See the possibilities rather than
the danger :-)

Peter

Jul 18 '05 #3
On 7 Sep 2003 11:26:28 -0700, da*******@yahoo .com (dan) wrote:
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).

This fact is *deeply* buried in the docs, and is not at all intuitive.
One of the big advantages of a high-level language such as Python is
the ability to provide run-time bounds checking on array-type
constructs. To achieve this I will now have to subclass my objects
and add it myself, which seems silly and will add significant
overhead. If you want this behavior, how hard is it to say a = b[x %
len(b)] ??
That isn't really the exact behavior. E.g.,
range(5) [0, 1, 2, 3, 4] range(5)[-4] 1 range(5)[-5] 0 range(5)[-6] Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
range(5)[4] 4 range(5)[5]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
Can anyone explain why this anomaly exists, and why it should continue
to exist?

It has apparently proven more useful to have it so than not, though I sympathize
with your frustration in for your use.

Perhaps a .no_negative_in dexing attribute or something could be added to the C implementation,
so that you could specify your desired checking without a performance hit.

Meanwhile, maybe an assert i>=0 in the index-supplier side of the contract might work too?

Regards,
Bengt Richter
Jul 18 '05 #4

"dan" <da*******@yaho o.com> wrote in message
news:fb******** *************** ***@posting.goo gle.com...
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).
No, it adds len(seq). Changing + to % would be slower and more
obscure.
This fact is *deeply* buried in the docs,
No more so than everything else in chapter subsections. From the Ref
Man table of contents I went directly to the most obvious place 5.3.2
Subscriptions, and found
'''
If the primary is a sequence, the expression (list) must evaluate to a
plain integer. If this value is negative, the length of the sequence
is added to it (so that, e.g., x[-1] selects the last item of x.) The
resulting value must be a nonnegative integer less than the number of
items in the sequence, and the subscription selects the item whose
index is that value (counting from zero).
'''
Translated to Python, letting idex be result of index expression:

if not isinstance(idex , (int,long)): raise TypeError()
if idex < 0: idex += seqlen
if idex < 0 or idex >= seqlen: raise IndexError()
<get seq[idex]>
and is not at all intuitive.
Phrases like 'third from the end' are idiomatic English ;-)
One of the big advantages of a high-level language such as Python is the ability to provide run-time bounds checking on array-type
constructs. To achieve this I will now have to subclass my objects
and add it myself, which seems silly and will add significant
overhead. If you want this behavior, how hard is it to say a = b[x % len(b)] ??
Again, your innovation of using '% obscures rather than clarify.
Can anyone explain why this anomaly exists, and why it should continue to exist?


Being able to abbreviate seq(len(seq)-1] as seq[-1] is quite handy and
faster executing, , especially if seq is calculated from an
expression. Same for -2, etc. (And, of course, a change now would
break a noticeable fraction of existing programs.)

Terry J. Reedy
Jul 18 '05 #5
dan wrote:
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).
That is not the behavior of negative indices. Negative indices mean
index from the end of the sequence. So -1 means the _last_ element in
the list, -2 means the second to last element in the list, and so on.
-n (for n = len(seq) is the first element in the list.
This fact is *deeply* buried in the docs, and is not at all intuitive.
It's mentioned prominently (and early) in all the tutorials and books on
Python I've read, and it's a very common and convenient convention, so
I'm not sure how far you could have gotten through learning Python and
never been exposed to it.
One of the big advantages of a high-level language such as Python is
the ability to provide run-time bounds checking on array-type
constructs. To achieve this I will now have to subclass my objects
and add it myself, which seems silly and will add significant
overhead. If you want this behavior, how hard is it to say a = b[x %
len(b)] ??


That's simply not true. Negative indices have similar bounds
requirements. If you have a sequence of length n, then indices 0
through (n - 1) map to the elements of the sequence in order from left
to right, and indices -1 through -n map to the elements in order from
right to left. Indices greater than n or less than -n generate
IndexErrors. Bounds checking is always done, whether on positive or
negative indices.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ Then you give me that Judas Kiss / Could you hurt me more than this
\__/ Lamya
Jul 18 '05 #6
da*******@yahoo .com (dan) wrote in message news:<fb******* *************** ****@posting.go ogle.com>...
As is often the case, I think this comes down to documentation. While
the behavior is mentioned early in the tutorial, I found it difficult
to find it in the reference -- but whatever, we can chalk this up to
RTFM on my part.

My explanation of the behavior is correct however. list[a] always
equals list[a % len(list)]. A negative number mod N = its absolute
value subtracted from N:

a % n == n - abs(a) # where -n <= a <= 0

However if I want to count from the end of the list, I would of course
write
list[len(list)-a]. I wasn't really considering that the purpose of
this feature was to count from the end of a list, which I admit could
come in handy.

Thanks for the responses.

Fernando Perez <fp*******@yaho o.com> wrote in message news:<bj******* ***@peabody.col orado.edu>...
dan wrote:
I was recently surprised, and quite shocked in fact, to find that
Python treats negative indices into sequence types as if they were
mod(length-of-sequence), at least up to -len(seq).

This fact is *deeply* buried in the docs, and is not at all intuitive.


Very deeply indeed: section 3.1.4 of the beginner's tutorial:

http://www.python.org/doc/current/tu...00000000000000

Of all places, this is the section on lists:
>> a = ['spam', 'eggs', 100, 1234]


[... snip ...]
>> a[-2] 100>> a[1:-1]

['eggs', 100]
Can anyone explain why this anomaly exists, and why it should continue
to exist?


Because this 'anomaly' is incredibly useful in many contexts, as many others
have already pointed out. Rest assured that it will continue to exist,
probably for as long as the language is around. Better get to like it :)

Cheers,

f.


Heck, I like it simply because I can read lines from files and easily
chop off the newline.

myStr = f.readline()[0:-1]

That alone is worth it's wait in gold to me, never mind all the other
things it makes easy.
Jul 18 '05 #7
ms****@comshare .com (bigdog) writes:
myStr = f.readline()[0:-1]


this may eat you last character in the file (if last line does not end
with new line which happens, but this will not ::

myStr = f.readline().rs trip('\n')

but is 6 character longer :)

--

=*= Lukasz Pankowski =*=
Jul 18 '05 #8
da*******@yahoo .com (dan) hypothesizes:
My explanation of the behavior is correct however. list[a] always
equals list[a % len(list)]. A negative number mod N = its absolute
value subtracted from N:


Proof by counterexample:

Python 2.2.2 (#1, Feb 8 2003, 12:11:31)
[GCC 3.2] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
s = '0123'
s[-20 % len(s)] '0' s[-20]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
Your explanation of the behaviour is incorrect.

QED.
Jul 18 '05 #9

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

Similar topics

19
2609
by: David Abrahams | last post by:
Can anyone explain the logic behind the behavior of list slicing with negative strides? For example: >>> print range(10) I found this result very surprising, and would just like to see the rules written down somewhere. Thanks,
5
2135
by: andrea.gavana | last post by:
Hello NG, I was wondering if there is a faster/nicer method (than a for loop) that will allow me to find the elements (AND their indices) in a list that verify a certain condition. For example, assuming that I have a list like: mylist = I would like to find the indices of the elements in the list that are equal to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily
8
1602
by: Steven Bethard | last post by:
I have a list of strings that looks something like: lst = The parentheses in the labels indicate where an "annotation" starts and ends. So for example, the label '(*)' at index 2 of the list means that I have an annotation at (2, 2), and the labels '(*', '*', '(*', '*))' at indices 4 through 7 mean that I have an annotation at (4, 7) and an annotation at (6, 7).
5
2904
by: Ross MacGregor | last post by:
I have a very simple yet complicated problem. I want to generate a random list of indices (int's) for a container. Let's say I have a container with 10 items and I want a list of 3 random indices for that container. So I need to generate 3 unique numbers from integer range . There seems to be no simple and efficient way to do this. Any implementation I have come up with involves maintaining a list of
8
5171
by: Joakim Hove | last post by:
Hello, I have the following code: #define N 99 double *ptr; double *storage; int index; storage = calloc(N , sizeof(double));
3
2155
by: David Mathog | last post by:
This one is driving me slightly batty. The code in question is buried deep in somebody else's massive package but it boils down to this, two pointers are declared, the first is: char **resname which is part of the "atoms" structure that is passed into the function from the outside. I have not yet found where it is allocated but I'm reasonably sure from other chunks of this code that it was by:
11
3735
by: drtimhill | last post by:
I'm just starting out on Python, and am stumped by what appears an oddity in the way negative indices are handled. For example, to get the last character in a string, I can enter "x". To get the 2nd and 3rd to last, I can enter x etc. This is fine. Logically, I should be able to enter x to get the last and next to last characters. However, since Python doesn't distinguish between positive and negative zero, this doesn't work. Instead, I...
3
2119
by: GavinCrooks | last post by:
The indices method of slice doesn't seem to work quite how I would expect when reversing a sequence. For example : '43210' '43210' So a slice with a negative step (and nothing else) reverses the sequence. But what are the corresponding indices?
2
3893
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
9646
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
9483
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
10346
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
10157
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
10096
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
8982
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
7504
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
5386
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...
3
2887
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.