473,785 Members | 3,157 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1085

"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
2493
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
1766
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
4
2935
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 correct so no problems there. Gecko works as expected. Prior to entering the function I can slice the array being entered so I wouldn't expect an "Unexpected call to method or property access" (in IE 6). I guess its something silly but as of yet i'm...
108
6462
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
2617
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...
0
1595
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 compliance. We are using a commercial testsuite that is sold explicitely for such validation purposes. Now there occurs a problem, where the corresponding test produces a
23
2339
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 tree.items('alfa.': 'beta.'): -- Antoon Pardon
7
2215
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
7252
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...
0
9645
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
9480
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
10325
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
9950
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
7499
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
6740
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
5381
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...
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.