473,386 Members | 1,745 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

curious about slice behaviour

I just found out by accident, that slice indices can be larger than
the length of the object. For example
'test'[:50] 'test' 'test'[40:50]

''

I'd rather expected to be confronted with an IndexError.
(This is actually described in
http://docs.python.org/lib/typesseq.html, so my expectation was wrong :))

Does anybody know, why this is preferred to just raising an error?

Sep 5 '05 #1
2 1075

"Stephan Diehl" <st***********@gmx.net> wrote in message
news:pa****************************@gmx.net...
I just found out by accident, that slice indices can be larger than
the length of the object. For example
'test'[:50] 'test' 'test'[40:50]
''
I'd rather expected to be confronted with an IndexError.
(This is actually described in
http://docs.python.org/lib/typesseq.html,


in footnote 4
.so my expectation was wrong :))
Does anybody know, why this is preferred to just raising an error?


Slicing was intentially designed to always give an answer (given int
coords) and never say 'can't answer' (whether by exception or a None
return). This avoids having to call len() when you don't care and avoids
having to use try:...except:... or conditionalize the code when it is not
needed. For instance c=s[0:1] is equivalent to

c=s[0:min(1,len(s))] # if slice had to be exact, or

c = s and s[0] or '' # or

if s:
c = s[0]
else:
c = '' # or

try:
c = s[0]
except IndexError:
c = ''

People occasionally post buggy code which simply needs s[0] changed to
s[0:1].

The form s[i:], which I am sure you agree is useful, is effectively
equivalent to eithers[i:len(s)] or s[i:<maxint>]. The latter view
generalizes to iterables without a knowable length.

Terry J. Reedy

Sep 5 '05 #2
On Mon, 05 Sep 2005 14:26:14 -0400, Terry Reedy wrote:

"Stephan Diehl" <st***********@gmx.net> wrote in message
news:pa****************************@gmx.net...
I just found out by accident, that slice indices can be larger than
the length of the object. For example
> 'test'[:50] 'test' [...] Does anybody know, why this is preferred to just raising an error?


Slicing was intentially designed to always give an answer (given int
coords) and never say 'can't answer' (whether by exception or a None
return). This avoids having to call len() when you don't care and avoids
having to use try:...except:... or conditionalize the code when it is not
needed. For instance c=s[0:1] is equivalent to

c=s[0:min(1,len(s))] # if slice had to be exact, or

c = s and s[0] or '' # or

if s:
c = s[0]
else:
c = '' # or

try:
c = s[0]
except IndexError:
c = ''

People occasionally post buggy code which simply needs s[0] changed to
s[0:1].

The form s[i:], which I am sure you agree is useful, is effectively
equivalent to eithers[i:len(s)] or s[i:<maxint>]. The latter view
generalizes to iterables without a knowable length.


I do think that this is useful and can save some lines of code.
Just never expected this.

Terry J. Reedy



Sep 5 '05 #3

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

Similar topics

15
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 ...
2
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)...
4
by: F. Da Costa | last post by:
Hi, I was wondering whether someone could enlighten me as to the reason why the slice does not work in IE when the arr is passed in properly. Checked the values in the srcArr and they are...
108
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...
40
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...
0
by: Clemens Hintze | last post by:
Hello, I have a question concerning the usage of default constructed std::slice instances. Our company currently validate the GNU-G++ 3.4 compiler against the ISO/IEC 14882:2003 standard for...
23
by: Antoon Pardon | last post by:
Now slices are objects in python, I was wondering if slice notation will be usable outside subscribtion in the future. Will it ever be possible to write things like: a = 4:9 for key, value in...
7
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,...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...

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.