Re: Why Python does *SLICING* the way it does??
Antoon Pardon <[EMAIL PROTECTED]> 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 <[EMAIL PROTECTED]> Student of computational linguistics, Uppsala University, Sweden -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Reinhold Birkenfeld wrote: > Other possibility, probably faster when almost all keys in the range are in > the dictionary: > > class sdict(dict): > def __getitem__(self, index): > if isinstance(index, slice): > d = {} > for key in xrange(slice.start, slice.stop, slice.step): Hm. I wonder whether (x)range could be made accepting a slice as single argument... Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
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__(self, index): if isinstance(index, slice): d = {} for key in xrange(slice.start, slice.stop, slice.step): if key in self: d[key] = self[key] return d else: return dict.__getitem__(self, index) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Dan Bishop schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: >> Op 2005-04-21, Steve Holden schreef <[EMAIL PROTECTED]>: >> > [EMAIL PROTECTED] 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Roy Smith <[EMAIL PROTECTED]> writes: > Greg Ewing <[EMAIL PROTECTED]> 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 "", line 1, in ? File "", line 6, in __getitem__ TypeError: cannot compare complex numbers using <, <=, >, >= Somehow, that seems like a wart. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Greg Ewing <[EMAIL PROTECTED]> 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 :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] 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 counterintuitive. 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Dan Bishop wrote: > Antoon Pardon wrote: > > 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.fortran . -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
In article <[EMAIL PROTECTED]>, Greg Ewing <[EMAIL PROTECTED]> wrote: > Roy Smith wrote: > > > What would actually be cool is if Python were to support the normal math > > notation for open or closed intervals. > > > > foo = bar (1, 2) > > foo = bar (1, 2] > > foo = bar [1, 2) > > foo = bar [1, 2] > > > > That would certainly solve this particular problem, but the cost to the > > rest of the language syntax would be rather high :-) > > Not to mention the sanity of everyone's editors when > they try to do bracket matching! I have no doubt that somebody could teach emacs python-mode to correctly match half-open interval brackets. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] wrote: I disagree. Programming languages should not needlessly surprise people, and a newbie to Python probably expects that x[1:3] = [x[1],x[2],x[3]]. But said newbie's expectations will differ considerably depending on which other language he's coming from. So he's almost always going to be surprised one way or another. Python sensibly adopts a convention that long experience has shown to be practical, rather than trying to imitate any particular precedent. 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 Who says the Python programmer doesn't have a choice? class NewbieWarmFuzzyList(list): def __new__(cls, base, *args): obj = list.__new__(cls, *args) obj.base = base return obj def __getitem__(self, i): return list.__getitem__(self, i - self.base) # etc... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Roy Smith wrote: What would actually be cool is if Python were to support the normal math notation for open or closed intervals. > foo = bar (1, 2) foo = bar (1, 2] foo = bar [1, 2) foo = bar [1, 2] That would certainly solve this particular problem, but the cost to the rest of the language syntax would be rather high :-) Not to mention the sanity of everyone's editors when they try to do bracket matching! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon wrote: This is nonsens. table[i] = j, just associates value j with key i. That is the same independend from whether the keys can start from 0 or some other value. 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. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Ron wrote: [EMAIL PROTECTED] wrote: 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). > There are actually 4 different ways to slice Where s = 'abcd' With s[i,j] Foreword slices index, forward steps a, b, c, d i= 0, 1, 2, 3 j= 1, 2, 3, 4 s[0,4] = 'abcd' s[1,3] = 'bc' ... Minor correction to this. It's what I get for not realizing how late it was. Where s = 'abcd' With s[i:j:step] Positive slice index, (+1 step) a, b, c, d i= 0, 1, 2, 3 j= 1, 2, 3, 4 s[0:4] = 'abcd' s[1:3] = 'bc' Positive slice index, (-1 step) a, b, c, d i= 0, 1, 2, 3 j= -5, -4, -3, -2 s[3:-5:-1] = 'dcba' s[2:-4:-1] = 'cb' Negative slice index, (+1 step) a, b, c, d i= -4, -3, -2, -1 j= 1, 2, 3, 4 s[-4:4] = 'abcd' s[-3:3] = 'bc' Reverse slice index, (-1 step) a, b, c, d i= -4, -3, -2, -1 j= -5, -4, -3, -2 s[-1:-5:-1] = 'dcba' s[-2:-4:-1] = 'cb' Cheers, Ron_Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Paul Rubin wrote: "Dan Bishop" <[EMAIL PROTECTED]> writes: Name a problem space that inherently requires arrays to be 1-based rather than 0-based. "inherently" is too strong a word, since after all, we could do all our computing with Turing machines. Some algorithms are specified in terms of 1-based arrays. And most Fortran programs are written in terms of 1-based arrays. So if you want to implement a 1-based specification in Python, or write Python code that interoperates with Fortran code, you either need 1-based arrays in Python or else you need messy conversions all over your Python code. I write Python code that interoperates with Fortran code all the time (and write Fortran code that interoperates with Python code, too). Very, very rarely do I have to explicitly do any conversions. They only show up when a Fortran subroutine requires an index in its argument list. In Fortran, I do Fortran. In Python, I do Python. Yes, there is some effort required when translating some code or pseudo-code that uses 1-based indexing. Having done this a number of times, I haven't found it to be much of a burden. The book "Numerical Recipes in C" contains a lot of numerical subroutines written in C, loosely based on Fortran counterparts from the original Numerical Recipes book. The C routines are full of messy conversions from 0-based to 1-based. Ugh. I contend that if they had decided to just write the C versions as C instead of C-wishing-it-were-Fortran, they would have made a much better library. Still sucky, but that's another story. Again, this (along with nested scopes and various other things) was all figured out by the Algol-60 designers almost 50 years ago. In Algol-60 you could just say "integer x(3..20)" and get a 3-based array (I may have the syntax slightly wrong by now). It was useful and took care of this problem. There's nothing that stops you from writing a class that does this. I believe someone posted such a one to this thread. I have yet to see a concrete proposal on how to make lists operate like this. -- Robert Kern [EMAIL PROTECTED] "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
"Dan Bishop" <[EMAIL PROTECTED]> writes: > Name a problem space that inherently requires arrays to be 1-based > rather than 0-based. "inherently" is too strong a word, since after all, we could do all our computing with Turing machines. Some algorithms are specified in terms of 1-based arrays. And most Fortran programs are written in terms of 1-based arrays. So if you want to implement a 1-based specification in Python, or write Python code that interoperates with Fortran code, you either need 1-based arrays in Python or else you need messy conversions all over your Python code. The book "Numerical Recipes in C" contains a lot of numerical subroutines written in C, loosely based on Fortran counterparts from the original Numerical Recipes book. The C routines are full of messy conversions from 0-based to 1-based. Ugh. Again, this (along with nested scopes and various other things) was all figured out by the Algol-60 designers almost 50 years ago. In Algol-60 you could just say "integer x(3..20)" and get a 3-based array (I may have the syntax slightly wrong by now). It was useful and took care of this problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon wrote: > Op 2005-04-21, Steve Holden schreef <[EMAIL PROTECTED]>: > > [EMAIL PROTECTED] 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? > 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
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. Well, *needless* surprise of newbies is never a good thing. If it were, it wouldn't be needless, now would it? :-) Surprising newbies just to surprise newbies is just cruel, but there is room in this world for "it may suprise you now, but you'll thank us later" and situations where there is a "newbie way" and an "other way", and the "other" way is chosen because it's the easiest thing for the most people in the long run. 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Reinhold Birkenfeld schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: >> Op 2005-04-21, Reinhold Birkenfeld schreef <[EMAIL PROTECTED]>: >>> Antoon Pardon wrote: >>> I sometimes think python should have been more explicite here, using a marker for the start-index and end-index, may '^' and '$'. So if you wanted the last element you had to write: lst[$] And for the next to last element: lst[$ - 1] This would make accessing list elements counted from the rear almost just as easy as it is now but wouldn't interfere with the ask forgiveness programming style. >>> >>> How would you pass this argument to __getitem__? >> >> Well assuming lst.last, was the last index of lst, __getitem__ >> would get lst.last and lst.last - 1 passed. > > Then it would be an alias for len(lst)-1 ? In the context of current python lists yes. But if you would go further and allow lists to start from an other index than 0 then not. >>> What would be allowed, only '$-x' or also '$+x' or what else? >> >> Any expression where an int is allowed. > > Okay. > >>> What type would '$' be? >> >> It would be an int. > > Where would it be allowed? Only in subscriptions? Yes, the idea would be that the brackets indicate a scope where $ would be the last index and ^ would be the first index. So if you wanted the middle element you could do: lst[(^ + $) // 2] But outsides the brackets the scope where this has any meaning wouldn't be present. Not that I think this idea has any chance. Already I can hear people shout that this is too perlish. But here is another idea. Sometime ago I read about the possibility of python acquiring a with statement. So that instead of having to write: obj.inst1 ... obj.inst2 ... obj.inst1 ... You could write: with obj: .inst1 ... .inst2 ... .inst1 ... If this would get implemented we could think of a left bracked as implicitely exucting a with statement. If we then had a list like class where the start-index could be different from zero and which had properties first and last indicating the first and last index we could then write something like: lst[.last] for the last element or lst[.last - 1] for the next to last element. lst[.first] for the first element lst[(.first + .last) // 2] for the middle element Maybe this makes the proposal again pythonic enough to get a little consideration. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon wrote: > Op 2005-04-21, Reinhold Birkenfeld schreef <[EMAIL PROTECTED]>: >> Antoon Pardon wrote: >> >>> I sometimes think python should have been more explicite here, >>> using a marker for the start-index and end-index, may '^' and >>> '$'. So if you wanted the last element you had to write: >>> >>> lst[$] >>> >>> And for the next to last element: >>> >>> lst[$ - 1] >>> >>> >>> This would make accessing list elements counted from the rear >>> almost just as easy as it is now but wouldn't interfere with >>> the ask forgiveness programming style. >> >> How would you pass this argument to __getitem__? > > Well assuming lst.last, was the last index of lst, __getitem__ > would get lst.last and lst.last - 1 passed. Then it would be an alias for len(lst)-1 ? >> What would be allowed, only '$-x' or also '$+x' or what else? > > Any expression where an int is allowed. Okay. >> What type would '$' be? > > It would be an int. Where would it be allowed? Only in subscriptions? Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Steve Holden schreef <[EMAIL PROTECTED]>: > [EMAIL PROTECTED] wrote: >> Terry Hancock wrote: >> >> >> >>>So I like Python's slicing because it "bites *less*" than intervals >> >> in C or Fortran. >> >> I disagree. Programming languages should not needlessly surprise >> people, and a newbie to Python probably expects that x[1:3] = >> [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95, >> Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention, >> and I don't know of Fortran or R programmers who complain (don't follow >> Matlab enough to say). There are Python programmers, such as the OP and >> me, who don't like the Python convention. What languages besides Python >> use the Python slicing convention? >> > 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. >> 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). > Then when you read code you > would continually be asking yourself "is this a one-based or a > zero-based structure?", which is not a profitable use of time. No you wouldn't. If you have the choice you just take the start index that is more natural. Sometimes that is 0 sometimes that is 1 and other times it is some whole other number. The times I had the opportunity to use such structures, the question of whether it was zero-based or one-based, rarely popped up. Either it was irrelevant or it was clear from what you were processing. 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. The one obvious way is to use the same index scheme as the one that is used in the specification or problem setting. Not to use always zero no matter what. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Reinhold Birkenfeld schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: > >> I sometimes think python should have been more explicite here, >> using a marker for the start-index and end-index, may '^' and >> '$'. So if you wanted the last element you had to write: >> >> lst[$] >> >> And for the next to last element: >> >> lst[$ - 1] >> >> >> This would make accessing list elements counted from the rear >> almost just as easy as it is now but wouldn't interfere with >> the ask forgiveness programming style. > > How would you pass this argument to __getitem__? Well assuming lst.last, was the last index of lst, __getitem__ would get lst.last and lst.last - 1 passed. > What would be allowed, only '$-x' or also '$+x' or what else? Any expression where an int is allowed. > What type would '$' be? It would be an int. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon wrote: > I sometimes think python should have been more explicite here, > using a marker for the start-index and end-index, may '^' and > '$'. So if you wanted the last element you had to write: > > lst[$] > > And for the next to last element: > > lst[$ - 1] > > > This would make accessing list elements counted from the rear > almost just as easy as it is now but wouldn't interfere with > the ask forgiveness programming style. How would you pass this argument to __getitem__? What would be allowed, only '$-x' or also '$+x' or what else? What type would '$' be? Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] wrote: Terry Hancock wrote: So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. I disagree. Programming languages should not needlessly surprise people, and a newbie to Python probably expects that x[1:3] = [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95, Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention, and I don't know of Fortran or R programmers who complain (don't follow Matlab enough to say). There are Python programmers, such as the OP and me, who don't like the Python convention. What languages besides Python use the Python slicing convention? 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. 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? Then when you read code you would continually be asking yourself "is this a one-based or a zero-based structure?", which is not a profitable use of time. regards Steve -- Steve Holden+1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Raymond Hettinger schreef <[EMAIL PROTECTED]>: >> > [Antoon Pardon] >> >> I don't see why the start index can't be accessible through >> >> a method or function just like the length of a list is now. >> >> >> >> My favourite would be a range method so we would have >> >> the following idiom: >> >> >> >> for i in lst.range(): >> >> do something with lst[i] >> > >> > After going to all that trouble, you might as well also get the value at > that >> > position: >> > >> > for i, x in enumerate(lst): >> > do something with lst[i] also known as x >> >> No you wouldn't, enumerate always starts with 0. > > You don't get it. Your proposed list-like class indicates its start index. > enumerate() can be made to detect that start value so that the above code > always > works for both 0-based and 1-based arrays. Oh you mean if it would be made a buildin class. Personnally I would still prefer my range solution. I often find enumerate gives me too much. Often enough I want to assign new values to the elements in the list. I have no need for the old value, that is also provided by enumerate. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
> > [Antoon Pardon] > >> I don't see why the start index can't be accessible through > >> a method or function just like the length of a list is now. > >> > >> My favourite would be a range method so we would have > >> the following idiom: > >> > >> for i in lst.range(): > >> do something with lst[i] > > > > After going to all that trouble, you might as well also get the value at that > > position: > > > > for i, x in enumerate(lst): > > do something with lst[i] also known as x > > No you wouldn't, enumerate always starts with 0. You don't get it. Your proposed list-like class indicates its start index. enumerate() can be made to detect that start value so that the above code always works for both 0-based and 1-based arrays. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-21, Raymond Hettinger schreef <[EMAIL PROTECTED]>: > [Antoon Pardon] >> I don't see why the start index can't be accessible through >> a method or function just like the length of a list is now. >> >> My favourite would be a range method so we would have >> the following idiom: >> >> for i in lst.range(): >> do something with lst[i] > > After going to all that trouble, you might as well also get the value at that > position: > > for i, x in enumerate(lst): > do something with lst[i] also known as x No you wouldn't, enumerate always starts with 0. So if you write a class with list-like behaviour except that the start index can be different from 0, enumerate is useless because lst[i] won't be x in that case. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon <[EMAIL PROTECTED]> writes: > I sometimes think python should have been more explicite here, > using a marker for the start-index and end-index, may '^' and > '$'. So if you wanted the last element you had to write: > > lst[$] > > And for the next to last element: > > lst[$ - 1] I like this. I don't know how many times I've gotten screwed by wanting the n'th element from the last for variable n, and saying "lst[n]" then realizing I have a bug when n=0. lst[$-n] works perfectly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] wrote: 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 Hi Chris, What I've found is foreword slicing with positive stepping is very convenient for a lot of things. :-) But when you start trying to use reverse steps, it can get tricky. There are actually 4 different ways to slice and dice. So we have a pretty good choice. So the trick is to match the slice method to what you need, and also use the correct index's for that method. Where s = 'abcd' With s[i,j] Foreword slices index, forward steps a, b, c, d i= 0, 1, 2, 3 j= 1, 2, 3, 4 s[0,4] = 'abcd' s[1,3] = 'bc' Foreword slice index (-steps) a, b, c, d i= 0, 1, 2, 3 j= -5, -4, -3, -2 s[3,-5] = 'dcba' s[2,-4] = 'cb' Reverse slice index (+steps) a, b, c, d i= -4, -3, -2, -1 j= 1, 2, 3, 4 s[-4,4] = 'abcd' s[-3,3] = 'bc' Reverse slice index (-steps) a, b, c, d i= -4, -3, -2, -1 j= -5, -4, -3, -2 s[-1,-5] = 'dcba' s[-2,-4] = 'cb' (Maybe this could be made a little more symetrical for Python 3000?) Cheers, Ron_Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Terry Hancock schreef <[EMAIL PROTECTED]>: > On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote: >> Terry Hancock wrote: >> >> I used to make "off by one" errors all the time in both C and Fortran, >> >> whereas I hardly ever make them in Python. >> >> Part of the reason may be that most loops over lists involve >> iterators, > >> both endpoints are mentioned explicitly. C++/STL also uses iterators, >> but the syntax is repulsive. > > That's true of course. It's more likely to show up in manipulating > lists or strings. And Python provides a much richer environment for > processing strings, so one has to deal with explicit indexing much > less. > > But I still think that I make fewer error per instance of dealing with > intervals. It's rare that I even have to think about it much when > writing such a thing. Negative indexing also helps a lot. I'm anbivallent about negative indexes. It helps a lot, but can be annoying a lot too. IMO it deters from the, its easier to be forgiven than to get permission, style of programming. It happens rather regularly that I need to do some calculations and if the start conditions were good, I get a valid index for a list and otherwise I get an invalid index. From this specification the following seems a natural way to program try: index = calculate(...) lst[index] = ... ... except IndexError ... But of course this doesn't work because a negative index in this case is an invalid index but python allows it. I sometimes think python should have been more explicite here, using a marker for the start-index and end-index, may '^' and '$'. So if you wanted the last element you had to write: lst[$] And for the next to last element: lst[$ - 1] This would make accessing list elements counted from the rear almost just as easy as it is now but wouldn't interfere with the ask forgiveness programming style. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[Antoon Pardon] > I don't see why the start index can't be accessible through > a method or function just like the length of a list is now. > > My favourite would be a range method so we would have > the following idiom: > > for i in lst.range(): > do something with lst[i] After going to all that trouble, you might as well also get the value at that position: for i, x in enumerate(lst): do something with lst[i] also known as x Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Terry Hancock schreef <[EMAIL PROTECTED]>: > On Wednesday 20 April 2005 07:52 am, Antoon Pardon wrote: >> Personnaly I would like to have the choice. Sometimes I prefer to >> start at 0, sometimes at 1 and other times at -13 or +7. > > Although I would classify that as a "rare use case". So, it "ought > to be possible to do it, but not necessarily easy". The -13 and +7 may be rare cases, but I wouldn't call one as a start index a rare case. I often get data in files where each line is a record with delimited fields. When I ask which field contains certain data, I get an answer that depends on counting starting with one. So starting with one as index would seem the more natural choice here. As far as I'm concerend, 0 as a starting index is a rare use case. In the programs I write about 45% is a natural 1 for first index, about 50% is a don't care and 5% is a natural 0 first index and some fraction is others. So yes in most of my programs 0 as a starting index works fine, but that is because in a lot of programs it doesn't matter much which would be the first index. Now I can understand that for others the 0 as a natural start index is more frequent, but if we have two frequent use cases, it seems to me the language should provide the choice more easily as it does now. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Peter Hansen schreef <[EMAIL PROTECTED]>: > Terry Hancock wrote: >> However, I used to make "off by one" errors all the time in both C and >> Fortran, >> whereas I hardly ever make them in Python. > > This should probably be the overriding concern in this > case. > > I can't remember the last time I made an off-by-one error > in Python (or, really, whether I ever have), whereas I > can't remember the last C program I wrote which didn't have > one. I do so frequently. I often have to process files where each line is a record, each record having a number of fields seperated with a delimiter. So the idiom for treating such files has become for line in the_file: lst = line.split(delimiter) 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. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] wrote: > What languages besides Python use the Python slicing convention? Java uses it for the "substring" method of strings. > 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. Maybe less relevant, but relevant nonetheless. First, there's the desire for familiarity. Many Python programmers are also C programmers, and that fact has had an influence on the development of the language. That's why we write "x += 0x20" rather than "x := x + $20". Why not array indexing as well? More importantly, there are reasons for counting from zero that have nothing to do with pointers. The biggest reason involves modular arithmetic: r=n%d satifies 0 <= r < d, which conveniently matches Python's array syntax. DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] def weekday_name(date): return DAY_NAMES[date.toordinal() % 7] Modular arithmetic's preference for 0-based counting goes beyond array indexing. For example, consider our notation for time, from 00:00:00 to 23:59:59. def time_add(time, delta): """ time = an (hour, minute, second) tuple for a time of day delta = an (hour, minute, second) tuple for an amount of time Returns time+delta, as an (hour, minute, second) tuple. """ hour = time[0] + delta[0] minute = time[1] + delta[1] second = time[2] + delta[2] # Normalize the time second = ((hour * 60) + minute) * 60 + second minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) hour %= 24 return hour, minute, second Imagine that the time notation went from 01:01:01 to 24:60:60. Try writing a time_add function for that. The only simple way I can think of is to temporarily convert to zero-based notation! def time_add(time, delta): # Add like terms and convert to zero-based notation. hour = time[0] + delta[0] - 1 minute = time[1] + delta[1] - 1 second = time[2] + delta[2] - 1 # Normalize the time second = ((hour * 60) + minute) * 60 + second minute, second = divmod(second, 60) hour, minute = divmod(minute, 60) hour %= 24 # Convert back to one-based notation on output return hour + 1, minute + 1, second + 1 > 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. If you really want 1-based arrays, just do what most BASIC programmers do: Ignore x[0]. >>> months = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] >>> print months[4] Apr -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Roy Smith schreef <[EMAIL PROTECTED]>: > Antoon Pardon <[EMAIL PROTECTED]> wrote: >>Op 2005-04-20, Roy Smith schreef <[EMAIL PROTECTED]>: >>> Antoon Pardon <[EMAIL PROTECTED]> wrote: >>> Personnaly I would like to have the choice. Sometimes I prefer to start at 0, sometimes at 1 and other times at -13 or +7. >>> >>> Argggh. Having two (or more!) ways to do it, would mean that every time I >>> read somebody else's code, I would have to figure out which flavor they are >>> using before I could understand what their code meant. That would be evil. >> >>This is nonsens. table[i] = j, just associates value j with key i. >>That is the same independend from whether the keys can start from >>0 or some other value. Do you also consider it more ways because >>the keys can end in different values? > > There are certainly many examples where the specific value of the > first key makes no difference. A good example would be > > for element in myList: > print element > > On the other hand, what output does > >myList = ["spam", "eggs", "bacon"] >print myList[1] > > produce? In a language where some lists start with 0 and some start > with 1, I don't have enough information just by looking at the above > code. Yes you have. The fact that a language allows a choice doesn't contradict there is a default, when no choice is specified. My preference would be that it would produce "spam", because if you want the *first*" element, you want the element associated withe the key 1. Or maybe the language would force you to give a start index, so that you would have to write: MyList = [3 -> "spam", "eggs", "bacon"] End of course the language would provide instances or methods so you could ask what the first index was. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Bill Mill schreef <[EMAIL PROTECTED]>: > On 20 Apr 2005 13:39:42 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: >> Op 2005-04-20, Bill Mill schreef <[EMAIL PROTECTED]>: >> >> You write this af if other solutions can't be consistent. > > Propose one, and I won't write it off without thinking, but my bias is > way against it from experience. Knowledge gets scattered across the > program, Knowledge always gets scattered across the program. The end index can vary endlessly but that doesn't seem to worry you. So why is a varying start index so worrysome? > unless you're defining the start index every time you use the > list, which seems no better than adding an offset to me. I don't see why the start index can't be accessible through a method or function just like the length of a list is now. My favourite would be a range method so we would have the following idiom: for i in lst.range(): do something with lst[i] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon <[EMAIL PROTECTED]> writes: > Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: >> Hallöchen! >> >> [EMAIL PROTECTED] (Nick Efford) writes: >> >>> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >>>> 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). >>> >>> mystring[:4] can be read as "the first four characters of >>> mystring". If it included mystring[4], you'd have to read it as >>> "the first five characters of mystring", which wouldn't match the >>> appearance of '4' in the slice. >>> >>> [...] >>> >>> It all makes perfect sense when you look at it this way! >> >> Well, also in my experience every variant has its warts. You'll >> never avoid the "i+1" or "i-1" expressions in your indices or loops >> (or your mind ;). >> >> It's interesting to muse about a language that starts at "1" for all >> arrays and strings, as some more or less obsolete languages do. I >> think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting at >> "0" is easier memory address calculation, so nothing for really high >> level languages. > > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. Some HLLs have had arrays that let you declare the first index as well as the size for decades now. Algol-68, for instance. Modern language still offer such features, but none seem to have been very popular. Of course, in any reasonable OO language, you can roll your own. So the question comes down to whether or not these get into the standard library. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
James Carroll wrote: If you have five elements, numbered 0,1,2,3,4 and you ask for the elements starting with the first one, and so on for the length you would have [0:length]. So [0:5] gives you elemets 0,1,2,3,4. Think of the weirdess if you had to ask for [0:length-1] to get length elements... [...] It is a little weired that slicing does [index: count] instead of [index:index] or [count:count] I agree, but python really does just flow wonderfully once you see how clean code is that's written [index: count]. I think you got confused part way through that. Python's slices are *not* index:count, but are index:index. It's just that for the example you gave, starting at 0, they happen to amount to the same thing... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On Wednesday 20 April 2005 12:28 pm, Roy Smith wrote: > Terry Hancock wrote: > >> I used to make "off by one" errors all the time in both C and Fortran, > >> whereas I hardly ever make them in Python. > > Part of the reason may be that most loops over lists involve > iterators, > both endpoints are mentioned explicitly. C++/STL also uses iterators, > but the syntax is repulsive. That's true of course. It's more likely to show up in manipulating lists or strings. And Python provides a much richer environment for processing strings, so one has to deal with explicit indexing much less. But I still think that I make fewer error per instance of dealing with intervals. It's rare that I even have to think about it much when writing such a thing. Negative indexing also helps a lot. Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
"James Stroud" <[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] > I like this, it works for any integer. > >>> str="asdfjkl;" > >>> i=-400 > >>> print str[:i]+str[i:] > asdfjkl; > >>> i = 65534214 > >>> print str[:i]+str[i:] > asdfjkl; Actually, this has no relation with the half-open slices but with the fact that if i goes beyond the limit of the string then Python, wisely, doesn't raise an error but instead return the string until the end. When people say that half-open slices work for every i, they are tinking in the case i=0. Javier ___ Javier Bezos| TeX y tipografía jbezos at wanadoo dot es| http://perso.wanadoo.es/jbezos |... CervanTeX (Spanish TUG) | http://www.cervantex.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
<[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] > 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.) Recently there was a short (sub)thread about that. One of my messages (against half-open slices) is, for example http://groups-beta.google.com/group/comp.lang.python/msg/5532dd50b57853b1 Javier ___ Javier Bezos| TeX y tipografía jbezos at wanadoo dot es| http://perso.wanadoo.es/jbezos |... CervanTeX (Spanish TUG) | http://www.cervantex.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
I like this, it works for any integer. >>> str="asdfjkl;" >>> i=-400 >>> print str[:i]+str[i:] asdfjkl; >>> i = 65534214 >>> print str[:i]+str[i:] asdfjkl; Please forgive my reassigning str. I am one of those type first think later programmers. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
If you have five elements, numbered 0,1,2,3,4 and you ask for the elements starting with the first one, and so on for the length you would have [0:length]. So [0:5] gives you elemets 0,1,2,3,4. Think of the weirdess if you had to ask for [0:length-1] to get length elements... One based 1... n are what I call _counting numbers_ Zero based 0... n-1 are the _indexes_ (offsets) into the collection. The first element is at offset 0. It is a little weired that slicing does [index: count] instead of [index:index] or [count:count] I agree, but python really does just flow wonderfully once you see how clean code is that's written [index: count]. In C++ the STL also has the idea that there's an 'end()' iterator that is really one element past the end of your container. It makes things flow really well there too. All code interates up to but not including the last element you specify. always. -Jim On 19 Apr 2005 22:58:49 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On Tuesday 19 April 2005 10:58 pm, [EMAIL PROTECTED] wrote: > Many people I know ask why Python does slicing the way it does. > > Can anyone /please/ give me a good defense/justification??? Here you go, no remembering "+1" or "-1". Also, see the hundreds of other times this topic has graced this list. >>> i = 4 >>> str = "asdfjkl;" >>> print str[:i]+str[i:] asdfjkl; James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Terry Hancock wrote: >> I used to make "off by one" errors all the time in both C and Fortran, >> whereas I hardly ever make them in Python. Part of the reason may be that most loops over lists involve iterators, where the details of the index limits are hidden. In Python, you write: for item in myList: blah but in C and Fortran you would write: for (i = 0; i < MAXLIST; ++i) { blah; do 10 i = 1, MAXLIST 10blah both endpoints are mentioned explicitly. C++/STL also uses iterators, but the syntax is repulsive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
HallÃchen! Bernhard Herzog <[EMAIL PROTECTED]> writes: > Torsten Bronger <[EMAIL PROTECTED]> writes: > >>> http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF >> >> I see only one argument there: "Inclusion of the upper bound >> would then force the latter to be unnatural by the time the >> sequence has shrunk to the empty one." [...] > > The other main argument for startig at 0 is that if you do not > include the upper bound and start at 1 then the indices i of a > sequence of N values are 1 <= i < N + 1 which is not as nice as 0 > <= i < N. opportunity for an off by one error. The alternative is starting with 1 and using "lower <= i <= upper". (Dijkstra's second choice.) > Then there's also that, starting at 0, "an element's ordinal > (subscript) equals the number of elements preceding it in the > sequence." Granted, but you trade such elegancies for other uglinesses. A couple of times I changed the lower limit of some data structure from 0 to 1 or vice versa, and ended up exchanging a "+1" here for a "-1" there. It's a matter of what you are accustomed to, I suspect. We (programmers) think with the 0-notation, but non-spoiled minds probably not. TschÃ, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Torsten Bronger <[EMAIL PROTECTED]> writes: >> http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF > > I see only one argument there: "Inclusion of the upper bound would > then force the latter to be unnatural by the time the sequence has > shrunk to the empty one." While this surely is unaesthetical, I > don't think that one should optimise syntax according to this very > special case. The other main argument for startig at 0 is that if you do not include the upper bound and start at 1 then the indices i of a sequence of N values are 1 <= i < N + 1 which is not as nice as 0 <= i < N. opportunity for an off by one error. Then there's also that, starting at 0, "an element's ordinal (subscript) equals the number of elements preceding it in the sequence." Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Terry Hancock wrote: However, I used to make "off by one" errors all the time in both C and Fortran, whereas I hardly ever make them in Python. This should probably be the overriding concern in this case. I can't remember the last time I made an off-by-one error in Python (or, really, whether I ever have), whereas I can't remember the last C program I wrote which didn't have one. So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
HallÃchen! Bernhard Herzog <[EMAIL PROTECTED]> writes: > Torsten Bronger <[EMAIL PROTECTED]> writes: > >> It's interesting to muse about a language that starts at "1" for >> all arrays and strings, as some more or less obsolete languages >> do. I think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting >> at "0" is easier memory address calculation, so nothing for >> really high level languages. > > There are very good reasons for half-open intervals and starting > at 0 apart from memory organization. Dijkstra explained this > quite well in > http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF I see only one argument there: "Inclusion of the upper bound would then force the latter to be unnatural by the time the sequence has shrunk to the empty one." While this surely is unaesthetical, I don't think that one should optimise syntax according to this very special case. Besides, no language I know of has probems with negative values. Well, and the argument for "0" derives from that, according to Dijkstra. TschÃ, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Bernhard Herzog <[EMAIL PROTECTED]> writes: > There are very good reasons for half-open intervals and starting at 0 > apart from memory organization. Dijkstra explained this quite well in > http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Thanks for the excellent link! -- Aaron Bingham Software Engineer Cenix BioScience GmbH -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Torsten Bronger <[EMAIL PROTECTED]> writes: > It's interesting to muse about a language that starts at "1" for all > arrays and strings, as some more or less obsolete languages do. I > think this is more intuitive, since most people (including > mathematicians) start counting at "1". The reason for starting at > "0" is easier memory address calculation, so nothing for really high > level languages. There are very good reasons for half-open intervals and starting at 0 apart from memory organization. Dijkstra explained this quite well in http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On Wednesday 20 April 2005 07:52 am, Antoon Pardon wrote: > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. Although I would classify that as a "rare use case". So, it "ought to be possible to do it, but not necessarily easy". Which Python obliges you on --- you can easily create a relocatable list class that indexes and slices anyway you see fit, e.g.: >>> class reloc(list): ... def __init__(self, start, contents=()): ... self.start = start ... for item in contents: ... self.append(item) ... def __getitem__(self, index): ... if isinstance(index, slice): ... if (not (self.start <= index.start < self.start + len(self)) or ... not (self.start <= index.stop < self.start + len(self))): ... raise IndexError ... return self.__class__.__base__.__getitem__(self, slice(index.start-self.start, index.stop-self.start, index.step)) ... else: ... if not (self.start <= index < self.start + len(self)): ... raise IndexError ... return self.__class__.__base__.__getitem__(self, index - self.start) ... ... >>> >>> r = reloc(-13, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', >>> 'm', 'n', 'o', 'p', 'q']) >>> r[0] 'n' >>> r[-12] 'b' >>> r[-13] 'a' >>> r[-14] Traceback (most recent call last): File "", line 1, in ? File "", line 14, in __getitem__ IndexError >>> r[0] 'n' >>> r[3] 'q' >>> r[4] Traceback (most recent call last): File "", line 1, in ? File "", line 14, in __getitem__ IndexError >>> Note that I added the IndexError to avoid the bizarre results you get due to "negative indexing" in the list base class (now they would change behavior at -13 instead of at 0, which is counter- intuitive to say the least). Better to cry foul if an index out of range is called for in this case, because it's gotta be a bug. What do you think, should I send it to Useless Python? ;-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon <[EMAIL PROTECTED]> wrote: >Op 2005-04-20, Roy Smith schreef <[EMAIL PROTECTED]>: >> Antoon Pardon <[EMAIL PROTECTED]> wrote: >> >>> Personnaly I would like to have the choice. Sometimes I prefer to >>> start at 0, sometimes at 1 and other times at -13 or +7. >> >> Argggh. Having two (or more!) ways to do it, would mean that every time I >> read somebody else's code, I would have to figure out which flavor they are >> using before I could understand what their code meant. That would be evil. > >This is nonsens. table[i] = j, just associates value j with key i. >That is the same independend from whether the keys can start from >0 or some other value. Do you also consider it more ways because >the keys can end in different values? There are certainly many examples where the specific value of the first key makes no difference. A good example would be for element in myList: print element On the other hand, what output does myList = ["spam", "eggs", "bacon"] print myList[1] produce? In a language where some lists start with 0 and some start with 1, I don't have enough information just by looking at the above code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
> Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. Subclass from builtin list - and make the necessary adjustmenst yourself in an overloaded __getitem__. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On 20 Apr 2005 13:39:42 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: > Op 2005-04-20, Bill Mill schreef <[EMAIL PROTECTED]>: > > On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: > >> Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: > >> > Hallöchen! > >> > > >> > [EMAIL PROTECTED] (Nick Efford) writes: > >> > > >> >> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > >> >>> 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). > >> >> > >> >> mystring[:4] can be read as "the first four characters of > >> >> mystring". If it included mystring[4], you'd have to read it as > >> >> "the first five characters of mystring", which wouldn't match the > >> >> appearance of '4' in the slice. > >> >> > >> >> [...] > >> >> > >> >> It all makes perfect sense when you look at it this way! > >> > > >> > Well, also in my experience every variant has its warts. You'll > >> > never avoid the "i+1" or "i-1" expressions in your indices or loops > >> > (or your mind ;). > >> > > >> > It's interesting to muse about a language that starts at "1" for all > >> > arrays and strings, as some more or less obsolete languages do. I > >> > think this is more intuitive, since most people (including > >> > mathematicians) start counting at "1". The reason for starting at > >> > "0" is easier memory address calculation, so nothing for really high > >> > level languages. > >> > >> Personnaly I would like to have the choice. Sometimes I prefer to > >> start at 0, sometimes at 1 and other times at -13 or +7. > >> > > > > -1. You can start arrays at 0 or 1 (and arbitrary bases? I don't > > recall) in VB, and it's an unmitigated disaster. It adds needless > > complexity. > > Complexity that is now put on the programmers shoulders. > > If I have a table with indexes going from -13 to +7, I have to > add the offset myself if I want to use a list for that. > > > What our slicing system loses in elegance in a few cases, > > it more than makes up for in consistency throughout all programs. > > You write this af if other solutions can't be consistent. Propose one, and I won't write it off without thinking, but my bias is way against it from experience. Knowledge gets scattered across the program, unless you're defining the start index every time you use the list, which seems no better than adding an offset to me. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Roy Smith schreef <[EMAIL PROTECTED]>: > Antoon Pardon <[EMAIL PROTECTED]> wrote: > >> Personnaly I would like to have the choice. Sometimes I prefer to >> start at 0, sometimes at 1 and other times at -13 or +7. > > Argggh. Having two (or more!) ways to do it, would mean that every time I > read somebody else's code, I would have to figure out which flavor they are > using before I could understand what their code meant. That would be evil. This is nonsens. table[i] = j, just associates value j with key i. That is the same independend from whether the keys can start from 0 or some other value. Do you also consider it more ways because the keys can end in different values? -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Bill Mill schreef <[EMAIL PROTECTED]>: > On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: >> Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: >> > Hallöchen! >> > >> > [EMAIL PROTECTED] (Nick Efford) writes: >> > >> >> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >> >>> 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). >> >> >> >> mystring[:4] can be read as "the first four characters of >> >> mystring". If it included mystring[4], you'd have to read it as >> >> "the first five characters of mystring", which wouldn't match the >> >> appearance of '4' in the slice. >> >> >> >> [...] >> >> >> >> It all makes perfect sense when you look at it this way! >> > >> > Well, also in my experience every variant has its warts. You'll >> > never avoid the "i+1" or "i-1" expressions in your indices or loops >> > (or your mind ;). >> > >> > It's interesting to muse about a language that starts at "1" for all >> > arrays and strings, as some more or less obsolete languages do. I >> > think this is more intuitive, since most people (including >> > mathematicians) start counting at "1". The reason for starting at >> > "0" is easier memory address calculation, so nothing for really high >> > level languages. >> >> Personnaly I would like to have the choice. Sometimes I prefer to >> start at 0, sometimes at 1 and other times at -13 or +7. >> > > -1. You can start arrays at 0 or 1 (and arbitrary bases? I don't > recall) in VB, and it's an unmitigated disaster. It adds needless > complexity. Complexity that is now put on the programmers shoulders. If I have a table with indexes going from -13 to +7, I have to add the offset myself if I want to use a list for that. > What our slicing system loses in elegance in a few cases, > it more than makes up for in consistency throughout all programs. You write this af if other solutions can't be consistent. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Antoon Pardon <[EMAIL PROTECTED]> wrote: > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. Argggh. Having two (or more!) ways to do it, would mean that every time I read somebody else's code, I would have to figure out which flavor they are using before I could understand what their code meant. That would be evil. What would actually be cool is if Python were to support the normal math notation for open or closed intervals. Any of the following would make sense: foo = bar (1, 2) foo = bar (1, 2] foo = bar [1, 2) foo = bar [1, 2] That would certainly solve this particular problem, but the cost to the rest of the language syntax would be rather high :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Terry Hancock wrote: > So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. I disagree. Programming languages should not needlessly surprise people, and a newbie to Python probably expects that x[1:3] = [x[1],x[2],x[3]] . Array-oriented languages, such as Fortran 90/95, Matlab/Octave/Scilab, and S-Plus/R do not follow the Python convention, and I don't know of Fortran or R programmers who complain (don't follow Matlab enough to say). There are Python programmers, such as the OP and me, who don't like the Python convention. What languages besides Python use the Python slicing convention? 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
HallÃchen! Antoon Pardon <[EMAIL PROTECTED]> writes: > Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: > >> [...] >> >> It's interesting to muse about a language that starts at "1" for >> all arrays and strings, as some more or less obsolete languages >> do. I think this is more intuitive, since most people (including >> mathematicians) start counting at "1". The reason for starting >> at "0" is easier memory address calculation, so nothing for >> really high level languages. > > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. In HTBasic you have the choice between 0 and 1; there is a global source code directive for it. However, hardly anybody really wants to use HTBasic. TschÃ, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote: > Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: > > Hallöchen! > > > > [EMAIL PROTECTED] (Nick Efford) writes: > > > >> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > >>> 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). > >> > >> mystring[:4] can be read as "the first four characters of > >> mystring". If it included mystring[4], you'd have to read it as > >> "the first five characters of mystring", which wouldn't match the > >> appearance of '4' in the slice. > >> > >> [...] > >> > >> It all makes perfect sense when you look at it this way! > > > > Well, also in my experience every variant has its warts. You'll > > never avoid the "i+1" or "i-1" expressions in your indices or loops > > (or your mind ;). > > > > It's interesting to muse about a language that starts at "1" for all > > arrays and strings, as some more or less obsolete languages do. I > > think this is more intuitive, since most people (including > > mathematicians) start counting at "1". The reason for starting at > > "0" is easier memory address calculation, so nothing for really high > > level languages. > > Personnaly I would like to have the choice. Sometimes I prefer to > start at 0, sometimes at 1 and other times at -13 or +7. > -1. You can start arrays at 0 or 1 (and arbitrary bases? I don't recall) in VB, and it's an unmitigated disaster. It adds needless complexity. What our slicing system loses in elegance in a few cases, it more than makes up for in consistency throughout all programs. Peace Bill Mill bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Raymond Hettinger <[EMAIL PROTECTED]> wrote: ><[EMAIL PROTECTED]> >> Many people I know ask why Python does slicing the way it does. >Python's way has some useful properties: > >* s == s[:i] + s[i:] > >* len(s[i:j]) == j-i # if s is long enough The latter being particularly helpful when i = 0 -- the first n elements are s[:n] . (Similarly elegantly, although of no practical significance, s == s[0:len(s)] .) -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Op 2005-04-20, Torsten Bronger schreef <[EMAIL PROTECTED]>: > Hallöchen! > > [EMAIL PROTECTED] (Nick Efford) writes: > >> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >>> 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). >> >> mystring[:4] can be read as "the first four characters of >> mystring". If it included mystring[4], you'd have to read it as >> "the first five characters of mystring", which wouldn't match the >> appearance of '4' in the slice. >> >> [...] >> >> It all makes perfect sense when you look at it this way! > > Well, also in my experience every variant has its warts. You'll > never avoid the "i+1" or "i-1" expressions in your indices or loops > (or your mind ;). > > It's interesting to muse about a language that starts at "1" for all > arrays and strings, as some more or less obsolete languages do. I > think this is more intuitive, since most people (including > mathematicians) start counting at "1". The reason for starting at > "0" is easier memory address calculation, so nothing for really high > level languages. Personnaly I would like to have the choice. Sometimes I prefer to start at 0, sometimes at 1 and other times at -13 or +7. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
On Wednesday 20 April 2005 01:36 am, Raymond Hettinger wrote: > <[EMAIL PROTECTED]> > > Many people I know ask why Python does slicing the way it does. [...] > Python's way has some useful properties: [...] > OTOH, it has some aspects that bite: [...] > I suspect that whether it feels natural depends on your previous background > and > whether you're working in an environment with arrays indexed from one or from > zero. For instance, C programmers are used to seeing code like: for(i=0 ; > i 1 > to N: a[I]=f(I); NEXT.Hence, the C coders may find Python's a[:n] to be > more natural than BASIC programmers. Well, I learned Basic, Fortran, C, Python --- more or less. And I first found Python's syntax confusing as it didn't follow the same rules as any of the previous ones. However, I used to make "off by one" errors all the time in both C and Fortran, whereas I hardly ever make them in Python. So I like Python's slicing because it "bites *less*" than intervals in C or Fortran. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
HallÃchen! [EMAIL PROTECTED] (Nick Efford) writes: > [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >> 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). > > mystring[:4] can be read as "the first four characters of > mystring". If it included mystring[4], you'd have to read it as > "the first five characters of mystring", which wouldn't match the > appearance of '4' in the slice. > > [...] > > It all makes perfect sense when you look at it this way! Well, also in my experience every variant has its warts. You'll never avoid the "i+1" or "i-1" expressions in your indices or loops (or your mind ;). It's interesting to muse about a language that starts at "1" for all arrays and strings, as some more or less obsolete languages do. I think this is more intuitive, since most people (including mathematicians) start counting at "1". The reason for starting at "0" is easier memory address calculation, so nothing for really high level languages. But most programmers are used to do it the Python (and most other languages) way, so this opportunity has been missed for good. TschÃ, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > 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). mystring[:4] can be read as "the first four characters of mystring". If it included mystring[4], you'd have to read it as "the first five characters of mystring", which wouldn't match the appearance of '4' in the slice. Given another slice like mystring[2:4], you know instantly by looking at the slice indices that this contains 4-2 = 2 characters from the original string. If the last index were included in the slice, you'd have to remember to add 1 to get the number of characters in the sliced string. It all makes perfect sense when you look at it this way! Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
Raymond Hettinger wrote: > to seeing code like: for(i=0 ; i BASIC programmer may be used to FOR I = 1 to N: a[I]=f(I); NEXT. Afaik, at least BBC BASIC uses zero based arrays :-) Maybe ZX Spectrum Basic too (too long ago to remember). -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
<[EMAIL PROTECTED]> > Many people I know ask why Python does slicing the way it does. Half open intervals are just one way of doing things. Each approach has its own merits and issues. Python's way has some useful properties: * s == s[:i] + s[i:] * len(s[i:j]) == j-i # if s is long enough OTOH, it has some aspects that bite: * It is awkward with negative strides such as with s[4:2:-1]. This was the principal reason for introducing the reversed() function. * It makes some people cringe when they first see it (you're obviously in that group). I suspect that whether it feels natural depends on your previous background and whether you're working in an environment with arrays indexed from one or from zero. For instance, C programmers are used to seeing code like: for(i=0 ; ihttp://mail.python.org/mailman/listinfo/python-list
Re: Why Python does *SLICING* the way it does??
>>>>> "[EMAIL PROTECTED]" == [EMAIL PROTECTED] navy mil <[EMAIL PROTECTED]> >>>>> writes: > Many people I know ask why Python does slicing the way it does. > Can anyone /please/ give me a good defense/justification??? Try http://www.everything2.com/index.pl?node_id=1409551 Ganesan -- Ganesan Rajagopal (rganesan at debian.org) | GPG Key: 1024D/5D8C12EA Web: http://employees.org/~rganesan| http://rganesan.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
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 -- http://mail.python.org/mailman/listinfo/python-list