473,799 Members | 3,017 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 3988

Dan Bishop wrote:
Antoon Pardon wrote:


<snip>
Like users have a choice in how long they make a list, they
should have a choice where the indexes start. (And that
shouldn't be limited to 0 and 1).


Suppose you could. Then what should

([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4)

equal?


Assuming the + sign means concatenate (as it does for Python lists)
rather than add (as it does for Numeric or Numarray arrays), it would
be

([3,1,4,1,5,9] indexbase 0)

since 0 would still be the default indexbase. If the user wanted a
1-based list as a result, he would use an expression such as

(([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4) indexbase 1)

If + means add, the result would be

([4,6,13] indexbase 0) .

Adding arrays makes sense if they have the same number of elements --
they do not need to have the same indices.

I rarely see problems caused by flexible lower array bounds mentioned
in comp.lang.fortr an .

Jul 19 '05 #41
be*******@aol.c om writes:
Suppose you could. Then what should
([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4)
equal?
If + means add, the result would be ([4,6,13] indexbase 0) .


That's counterintuitiv e. I'd expect c = a + b to result in c[i] =
a[i]+b[i] for all elements. So, for example,
([0,1,2,3,4] indexbase 0) + ([2,3] indexbase 2)
should result in ([0,1,4,6,4] indexbase 0)
and ([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4)
should either result in ([3,1,4,0,1,5,9] indexbase 0) or
else raise an exception.
Jul 19 '05 #42
Greg Ewing <gr**@cosc.cant erbury.ac.nz> wrote:
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. :-)


Of course you can slice them, you just have to subclass dict! The
following was about 15 minutes work:

---------------
import types

class slicableDict (dict):
def __getitem__ (self, index):
if type (index) == types.SliceType :
d2 = slicableDict()
for key in self.keys():
if key >= index.start and key < index.stop:
d2[key] = self[key]
return d2
else:
return dict.__getitem_ _ (self, index)

d = slicableDict()
d['hen'] = 1
d['ducks'] = 2
d['geese'] = 3
d['oysters'] = 4
d['porpoises'] = 5

print d
print d['a':'m']
---------------

Roy-Smiths-Computer:play$ ./slice.py
{'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2}
{'hen': 1, 'geese': 3, 'ducks': 2}

I defined d[x:y] as returning a new dictionary which contains those items
from the original whose keys are in the range x <= key < y. I'm not sure
this is terribly useful but it's a neat demonstration of just how simple
Python makes it to do stuff like this. I can't imagine how much work it
would be to add a similar functionality to something like C++ multimap.

I'm sure the code above could be improved, and I know I've ignored all
sorts of things like steps, and error checking. Frankly, I'm amazed this
worked at all; I expected to get a syntax error when I tried to create a
slice with non-numeric values.

PS: Extra credit if you can identify the set of keys I used without
resorting to google :-)
Jul 19 '05 #43
Roy Smith <ro*@panix.co m> writes:
Greg Ewing <gr**@cosc.cant erbury.ac.nz> wrote:
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. :-)


Of course you can slice them, you just have to subclass dict! The
following was about 15 minutes work:

---------------
import types

class slicableDict (dict):
def __getitem__ (self, index):
if type (index) == types.SliceType :
d2 = slicableDict()
for key in self.keys():
if key >= index.start and key < index.stop:
d2[key] = self[key]
return d2
else:
return dict.__getitem_ _ (self, index)

d = slicableDict()
d['hen'] = 1
d['ducks'] = 2
d['geese'] = 3
d['oysters'] = 4
d['porpoises'] = 5

print d
print d['a':'m']
---------------


I couldn't resist:

py> d = slicableDict()
py> d[3j] = 1
py> d[4j] = 2
py> d[5j] = 3
py> d[6j] = 4
py> d[4j:5j]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __getitem__
TypeError: cannot compare complex numbers using <, <=, >, >=

Somehow, that seems like a wart.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 19 '05 #44
Op 2005-04-21, Dan Bishop schreef <da*****@yahoo. com>:
Antoon Pardon wrote:
Op 2005-04-21, Steve Holden schreef <st***@holdenwe b.com>:
> be*******@aol.c om wrote: ... >> 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, as in Fortran or VBA. In C starting at >> 0 may be justified because of the connection between array subscripting >> and pointer arithmetic, but Python is a higher-level language where >> such considerations are less relevant.
>>
> But Pythonicity required that there should be one obvious way to do > something. How obvious is having two ways?


How obvious is that lists can be any length? Do you consider it
an unbounded number of ways, that lists can be any length?

Like users have a choice in how long they make a list, they
should have a choice where the indexes start. (And that
shouldn't be limited to 0 and 1).


Suppose you could. Then what should

([3, 1, 4] indexbase 0) + ([1, 5, 9] indexbase 4)

equal?


There are multiple possibilities, that can make sense.
I'm sure that no consensus will be reached about what
is should be. This will stop this idea from ever being
implemented. So you shouldn't worry too much about it :-).
That you are forced to use zero-based structures, while the
problem space you are working on uses one-based structures
is a far bigger stumbling block where you continually have
to be aware that the indexes in your program are one off
from the indexes the problem is expressed in.


Name a problem space that inherently requires arrays to be 1-based
rather than 0-based.


None, but that is beside the question. If I look into my mathematics
books plenty of problems are described in terms of one based indexes
Sure most of them could just as easily be described in terms of
zero-based indexes, but the fact of the matter is they are not.

The same goes for problems other people would like me to solve.
Often enough they describe their problems in term of 1-based
indexes rather than 0-based. Sure I can translate it to 0-based,
but that will just make communication between me and the client
more difficult.

--
Antoon Pardon
Jul 19 '05 #45
Roy Smith wrote:
import types

class slicableDict (dict):
def __getitem__ (self, index):
if type (index) == types.SliceType :
d2 = slicableDict()
for key in self.keys():
if key >= index.start and key < index.stop:
d2[key] = self[key]
return d2
else:
return dict.__getitem_ _ (self, index) [...]
Roy-Smiths-Computer:play$ ./slice.py
{'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2}
{'hen': 1, 'geese': 3, 'ducks': 2}

I defined d[x:y] as returning a new dictionary which contains those items
from the original whose keys are in the range x <= key < y. I'm not sure
this is terribly useful but it's a neat demonstration of just how simple
Python makes it to do stuff like this. I can't imagine how much work it
would be to add a similar functionality to something like C++ multimap.


Other possibility, probably faster when almost all keys in the range are in
the dictionary:

class sdict(dict):
def __getitem__(sel f, index):
if isinstance(inde x, slice):
d = {}
for key in xrange(slice.st art, slice.stop, slice.step):
if key in self:
d[key] = self[key]
return d
else:
return dict.__getitem_ _(self, index)

Reinhold
Jul 19 '05 #46
Reinhold Birkenfeld wrote:
Other possibility, probably faster when almost all keys in the range are in
the dictionary:

class sdict(dict):
def __getitem__(sel f, index):
if isinstance(inde x, slice):
d = {}
for key in xrange(slice.st art, slice.stop, slice.step):


Hm. I wonder whether (x)range could be made accepting a slice as single argument...

Reinhold
Jul 19 '05 #47
Rocco Moretti wrote:
Steve Holden wrote:
The principle of least surprise is all very well, but "needless
surprise of newbies" is a dangerous criterion to adopt for programming
language design and following it consistently would lead to a mess
like Visual Basic, which grew by accretion until Microsoft realized it
was no longer tenable and broke backward compatibility.

...
But I agree, having "the easiest thing for newbies" as your sole
criterion for language design is a road to madness, for no other reason
than that newbies don't stay newbies forever.


If Visual BASIC is the example of "easiest thing for newbies",
then it disproves your theory already. I think VB newbies
*do* stay newbies forever (or as long as they are using just VB).

-Peter
Jul 19 '05 #48
In article <3c************ *@individual.ne t>,
Reinhold Birkenfeld <re************ ************@wo lke7.net> wrote:
Roy Smith wrote:
import types

class slicableDict (dict):
def __getitem__ (self, index):
if type (index) == types.SliceType :
d2 = slicableDict()
for key in self.keys():
if key >= index.start and key < index.stop:
d2[key] = self[key]
return d2
else:
return dict.__getitem_ _ (self, index)

[...]
Roy-Smiths-Computer:play$ ./slice.py
{'oysters': 4, 'hen': 1, 'porpoises': 5, 'geese': 3, 'ducks': 2}
{'hen': 1, 'geese': 3, 'ducks': 2}

I defined d[x:y] as returning a new dictionary which contains those items
from the original whose keys are in the range x <= key < y. I'm not sure
this is terribly useful but it's a neat demonstration of just how simple
Python makes it to do stuff like this. I can't imagine how much work it
would be to add a similar functionality to something like C++ multimap.


Other possibility, probably faster when almost all keys in the range are in
the dictionary:

class sdict(dict):
def __getitem__(sel f, index):
if isinstance(inde x, slice):
d = {}
for key in xrange(slice.st art, slice.stop, slice.step):
if key in self:
d[key] = self[key]
return d
else:
return dict.__getitem_ _(self, index)


The problem with that is it requires the keys to be integers.
Jul 19 '05 #49
Peter Hansen wrote:

<snip>
But I agree, having "the easiest thing for newbies" as your sole
criterion for language design is a road to madness, for no other reason than that newbies don't stay newbies forever.


If Visual BASIC is the example of "easiest thing for newbies",
then it disproves your theory already. I think VB newbies
*do* stay newbies forever (or as long as they are using just VB).


Much snobbery is directed at Visual Basic and other dialects of Basic
(they even have "basic" in their name), but I think VBA is better
designed than the prestigious C in some important ways.

Suppose you want to allocate a 2-D array at run-time and pass it to a
procedure. The VBA code is just

Option Explicit
Option Base 1

Sub make_matrix()
Dim x() As Double
Dim n1 As Integer, n2 As Integer
n1 = 2
n2 = 3
ReDim x(n1, n2)
Call print_matrix(x)
End Sub

Sub print_matrix(xm at() As Double)
Debug.Print UBound(xmat, 1), UBound(xmat, 2)
'do stuff with xmat
End Sub

It is trivial to allocate and pass multidimensiona l arrays in VBA, but
C requires expertise with pointers. The subroutine print_matrix can
query the dimensions of xmat, so they don't need to be passed as
separate arguments, as in C. The fact that is tricky to do simple
things is a sign of the poor design of C and similar languages, at
least for non-systems programming.

People bash VB as a language the corrupts a programmer and prevents him
from ever becoming a "real" programmer. Maybe VB programmers quickly
get so productive with it that they don't need to fuss with trickier
languages.

Jul 19 '05 #50

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
4388
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
9685
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
9538
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
10249
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...
0
10025
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...
0
9068
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...
0
5461
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...
0
5584
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2937
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.