473,786 Members | 2,399 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 3982
Roy Smith 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):
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.


Yes, but wasn't it thought as a replacement for a list?

Reinhold
Jul 19 '05 #51
In article <3c************ *@individual.ne t>,
Reinhold Birkenfeld <re************ ************@wo lke7.net> wrote:
Roy Smith 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):
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.


Yes, but wasn't it thought as a replacement for a list?


Originally, yes. I went off on a tangent with string-keyed slices.
Jul 19 '05 #52
be*******@aol.c om writes:
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.
C and VBA have totally different application domains. Given any two
such languages, it's almost a given that either one will be better
than the other "in some important ways".
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.
Since C was desinged as a systems programming language, evaluating
it's design for non-systems programming is a pointless exercise.

Personally, I think of C as a "portable assembler". You write
time-critical code, important applications, and the kernel in it. You
let your HLL compilers generate it. Other than that, you ignore it.
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.


I've not really heard a lot of nasty comments about VB, though I have
about BASIC. Nuts, I've said a lot of nasty things about BASIC. But VB
is so far removed from the BASICs I worked with that the point is
moot.

I have heard that VB is much more productive than "convention al
languages" (usually meaning C/C++/COBOL/etc.). Then again, this is
ture of modern "scripting" languages. That's where VB started life,
even though it's now compiled. So this should come as no surprise.

<mieke
--
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 #53
"be*******@aol. com" wrote:
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


Sounds more like poor C skills on your part. Here's a snippet from the Python
Imaging Library which takes a 2D array (im) and creates another one (imOut).

Imaging
ImagingRankFilt er(Imaging im, int size, int rank)
{
Imaging imOut = NULL;
int x, y;
int i, margin, size2;

/* check image characteristics */
if (!im || im->bands != 1 || im->type == IMAGING_TYPE_SP ECIAL)
return (Imaging) ImagingError_Mo deError();

/* check size of rank filter */
if (!(size & 1))
return (Imaging) ImagingError_Va lueError("bad filter size");

size2 = size * size;
margin = (size-1) / 2;

if (rank < 0 || rank >= size2)
return (Imaging) ImagingError_Va lueError("bad rank value");

/* create output image */
imOut = ImagingNew(im->mode, im->xsize - 2*margin, im->ysize - 2*margin);
if (!imOut)
return NULL;

... actual algorithm goes here ...

return imOut;
}

The "im" input object carries multidimensiona l data, as well as all other properties
needed to describe the contents. There are no separate arguments for the image
dimensions, nor any tricky pointer manipulations. A Python version of this wouldn't
be much different.

</F>

Jul 19 '05 #54
Antoon Pardon <ap*****@forel. vub.ac.be> writes:
The problem is that the fields in lst are associated
with a number that is off by one as they are normally
counted. If I go and ask my colleague which field
contains some specific data and he answers:
the 5th, I have to remind my self I want lst[4]

This is often a cause for errors.


It sounds like you should wrap that list in an object more reminding of
the source data, then.

--
Björn Lindström <bk**@stp.ling. uu.se>
Student of computational linguistics, Uppsala University, Sweden
Jul 19 '05 #55

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

Similar topics

7
2582
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
3549
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
2055
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
4387
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
2758
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
6025
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
10360
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
10163
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
10108
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,...
1
7510
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
6744
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
5397
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
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4064
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
3
2894
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.