More random python observations from a perl programmer
Tom Christiansen
tchrist at mox.perl.com
Thu Aug 19 15:18:37 EDT 1999
[courtesy cc of this posting mailed to cited author]
In comp.lang.python,
duncan at rcp.co.uk (Duncan Booth) writes:
:>GOTCHA: (high)
:> Lists don't autoallocate the way dictionaries do. So while this works
:> on two dictionaries:
:> new = {}
:> for key in old.keys:
:> new[key] = old[key]
:> This fails on two lists:
:> new = []
:> for i in old:
:> new[i] = old[i]
:This is meaningless and nothing to do with autoallocating. i is iterating
:over values not indexes. you get the effect you want here by writing
: for i in old:
: new.append(i)
You're right. I should have written
new = []
for i in range(0,len(old)):
new[i] = old[i]
And that certainly is parallel to the dictionary case. Dictionary
auto-allocate. Lists don't. It's a gotcha to a Perl programmer,
because he's using to having both hashes and arrays autoallocate.
Not, of course, that we need to copy things that way, since arrays and
hashes are firstclassy. :-) But you know what I mean.
--tom
--
"... an initial underscore already conveys strong feelings of
magicalness to a C programmer."
--Larry Wall in <1992Nov9.195250.23584 at netlabs.com>
More information about the Python-list
mailing list