By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,136 Members | 2,135 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,136 IT Pros & Developers. It's quick & easy.

Why Python does *SLICING* the way it does??

P: n/a
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 #1
Share this Question
Share on Google+
54 Replies


P: n/a
>>>>> "seberino@spawar" == seberino@spawar navy mil <se******@spawar.navy.mil> 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

Jul 19 '05 #2

P: n/a
<se******@spawar.navy.mil>
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 ;
i<n; i++) a[i]=f(i); In contrast, a BASIC programmer may be used to FOR 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.

As long as a language is consistent about its approach, you just get used to it
and it stops being an issue after a few days.
Raymond Hettinger
Jul 19 '05 #3

P: n/a
Raymond Hettinger wrote:
to seeing code like: for(i=0 ; i<n; i++) a[i]=f(i); In contrast, a
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
Jul 19 '05 #4

P: n/a
se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #5

P: n/a
Hallöchen!

nd*@no.spam.org (Nick Efford) writes:
se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #6

P: n/a
Op 2005-04-20, Torsten Bronger schreef <br*****@physik.rwth-aachen.de>:
Hallchen!

nd*@no.spam.org (Nick Efford) writes:
se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #7

P: n/a
On Wednesday 20 April 2005 01:36 am, Raymond Hettinger wrote:
<se******@spawar.navy.mil>
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<n; i++) a[i]=f(i); In contrast, a BASIC programmer may be used to FOR 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

Jul 19 '05 #8

P: n/a
Raymond Hettinger <py****@rcn.com> wrote:
<se******@spawar.navy.mil>
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 -- si***@chiark.greenend.org.uk -- 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 hlddre heafdes bce bump bump bump
Jul 19 '05 #9

P: n/a
Hallöchen!

Antoon Pardon <ap*****@forel.vub.ac.be> writes:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik.rwth-aachen.de>:
[...]

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
Jul 19 '05 #10

P: n/a
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik.rwth-aachen.de>:
Hallchen!

nd*@no.spam.org (Nick Efford) writes:
se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #11

P: n/a
Terry Hancock wrote:

<snip>
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.

Jul 19 '05 #12

P: n/a
Antoon Pardon <ap*****@forel.vub.ac.be> 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 :-)
Jul 19 '05 #13

P: n/a
Op 2005-04-20, Bill Mill schreef <bi*******@gmail.com>:
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik.rwth-aachen.de>:
> Hallchen!
>
> nd*@no.spam.org (Nick Efford) writes:
>
>> se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #14

P: n/a
Op 2005-04-20, Roy Smith schreef <ro*@panix.com>:
Antoon Pardon <ap*****@forel.vub.ac.be> 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
Jul 19 '05 #15

P: n/a
On 20 Apr 2005 13:39:42 GMT, Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-04-20, Bill Mill schreef <bi*******@gmail.com>:
On 20 Apr 2005 12:52:19 GMT, Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-04-20, Torsten Bronger schreef <br*****@physik.rwth-aachen.de>:
> Hallchen!
>
> nd*@no.spam.org (Nick Efford) writes:
>
>> se******@spawar.navy.mil <se******@spawar.navy.mil> 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
Jul 19 '05 #16

P: n/a
> 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
Jul 19 '05 #17

P: n/a
Antoon Pardon <ap*****@forel.vub.ac.be> wrote:
Op 2005-04-20, Roy Smith schreef <ro*@panix.com>:
Antoon Pardon <ap*****@forel.vub.ac.be> 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.
Jul 19 '05 #18

P: n/a
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 "<stdin>", line 1, in ?
File "<stdin>", line 14, in __getitem__
IndexError r[0] 'n' r[3] 'q' r[4] Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", 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

Jul 19 '05 #19

P: n/a
Torsten Bronger <br*****@physik.rwth-aachen.de> 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/
Jul 19 '05 #20

P: n/a
Bernhard Herzog <bh@intevation.de> 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
--------------------------------------------------------------------

Jul 19 '05 #21

P: n/a
Hallöchen!

Bernhard Herzog <bh@intevation.de> writes:
Torsten Bronger <br*****@physik.rwth-aachen.de> 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
Jul 19 '05 #22

P: n/a
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
Jul 19 '05 #23

P: n/a
Torsten Bronger <br*****@physik.rwth-aachen.de> 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/
Jul 19 '05 #24

P: n/a
Hallöchen!

Bernhard Herzog <bh@intevation.de> writes:
Torsten Bronger <br*****@physik.rwth-aachen.de> 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
Jul 19 '05 #25

P: n/a
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
10 blah

both endpoints are mentioned explicitly. C++/STL also uses iterators,
but the syntax is repulsive.
Jul 19 '05 #26

P: n/a
On Tuesday 19 April 2005 10:58 pm, se******@spawar.navy.mil 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/
Jul 19 '05 #27

P: n/a
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, se******@spawar.navy.mil
<se******@spawar.navy.mil> 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

Jul 19 '05 #28

P: n/a
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/
Jul 19 '05 #29

P: n/a

<se******@spawar.navy.mil> escribi en el mensaje
news:11**********************@o13g2000cwo.googlegr oups.com...
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/...32dd50b57853b1

Javier

__________________________________________________ _________
Javier Bezos | TeX y tipografa
jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos
.............................|.................... ...........
CervanTeX (Spanish TUG) | http://www.cervantex.org



Jul 19 '05 #30

P: n/a

"James Stroud" <js*****@mbi.ucla.edu> escribi en el mensaje
news:ma**************************************@pyth on.org...
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 tipografa
jbezos at wanadoo dot es | http://perso.wanadoo.es/jbezos
.............................|.................... ...........
CervanTeX (Spanish TUG) | http://www.cervantex.org


Jul 19 '05 #31

P: n/a
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

Jul 19 '05 #32

P: n/a
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
Jul 19 '05 #33

P: n/a
"Dan Bishop" <da*****@yahoo.com> 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.
Jul 19 '05 #34

P: n/a
Paul Rubin wrote:
"Dan Bishop" <da*****@yahoo.com> 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
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 19 '05 #35

P: n/a
Ron
Ron wrote:
se******@spawar.navy.mil 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
Jul 19 '05 #36

P: n/a
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
Jul 19 '05 #37

P: n/a
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
Jul 19 '05 #38

P: n/a
be*******@aol.com 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
Jul 19 '05 #39

P: n/a
In article <3c*************@individual.net>,
Greg Ewing <gr**@cosc.canterbury.ac.nz> 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.
Jul 19 '05 #40

P: n/a

Dan Bishop wrote:
Antoon Pardon wrote:


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


Suppose you could. Then what should

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

equal?


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

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

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

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

If + means add, the result would be

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

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

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

Jul 19 '05 #41

P: n/a
be*******@aol.com 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.
Jul 19 '05 #42

P: n/a
Greg Ewing <gr**@cosc.canterbury.ac.nz> wrote:
Also, everyone, please keep in mind that you always have
the option of using a *dictionary*, in which case your
indices can start wherever you want.

You can't slice them, true, but you can't have everything. :-)


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

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

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

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

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

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

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

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

PS: Extra credit if you can identify the set of keys I used without
resorting to google :-)
Jul 19 '05 #43

P: n/a
Roy Smith <ro*@panix.com> writes:
Greg Ewing <gr**@cosc.canterbury.ac.nz> wrote:
Also, everyone, please keep in mind that you always have
the option of using a *dictionary*, in which case your
indices can start wherever you want.

You can't slice them, true, but you can't have everything. :-)


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

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

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

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

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


I couldn't resist:

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

Somehow, that seems like a wart.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 19 '05 #44

P: n/a
Op 2005-04-21, Dan Bishop schreef <da*****@yahoo.com>:
Antoon Pardon wrote:
Op 2005-04-21, Steve Holden schreef <st***@holdenweb.com>:
> be*******@aol.com wrote: ... >> Along the same lines, I think the REQUIREMENT that x[0] rather than >> x[1] be the first element of list x is a mistake. At least the
>> programmer should have a choice, as in Fortran or VBA. In C starting at >> 0 may be justified because of the connection between array subscripting >> and pointer arithmetic, but Python is a higher-level language where >> such considerations are less relevant.
>>
> But Pythonicity required that there should be one obvious way to do > something. How obvious is having two ways?


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

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


Suppose you could. Then what should

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

equal?


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


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


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

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

--
Antoon Pardon
Jul 19 '05 #45

P: n/a
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
Jul 19 '05 #46

P: n/a
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
Jul 19 '05 #47

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

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


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

-Peter
Jul 19 '05 #48

P: n/a
In article <3c*************@individual.net>,
Reinhold Birkenfeld <re************************@wolke7.net> wrote:
Roy Smith wrote:
import types

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

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

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


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

class sdict(dict):
def __getitem__(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)


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

P: n/a
Peter Hansen wrote:

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


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


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

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

Option Explicit
Option Base 1

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

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

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

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

Jul 19 '05 #50

54 Replies

This discussion thread is closed

Replies have been disabled for this discussion.