by simon baird

Friday, September 19, 2008

just when you thought i was over it...

~> python
Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:40) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = []
>>> a[0] = 'foo' # FAIL!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
~> irb
irb(main):001:0> a = []
=> []
irb(main):002:0> a[0] = 'foo'
=> "foo"
irb(main):003:0> a[5] = 'bar' # for extra credit...
=> "bar"
irb(main):004:0> a
=> ["foo", nil, nil, nil, nil, "bar"]
irb(main):005:0> exit

I think that this speaks for itself, don't you... :)

(It's late on Friday afternoon. I'm procrastinating...)

(Yes I know I can use a.append('foo'). But this did come up in a real world scenario where append wasn't quite what I wanted).

Check the comments for some discussion...


otherchirps said...

Explicit is better than implicit. :)

Makes sense to me -- it's an empty list. There is no slot zero to stash stuff in yet.

Could always try something like this:

>>> a = [None] * 6
>>> a[0] = "foo"
>>> a[5] = "bar"
>>> a
['foo', None, None, None, None, 'bar']

FND said...

I agree with otherchirps; this is a deliberate design feature in Python, and a good one IMHO.

Of course these things usually come down to personal preference, so the whole Ruby vs. Python flamewar is a bit pointless (though it can also be somewhat educating at times).

simon said...

well if explicit beats implicit perhaps we should use java... lol. in this example ruby says (in the voice of handy andy from uk changing rooms), "right well, you know what you want, let's do it then shall we". python says (in a little britain computer says no voice or perhaps a monty python shopping lady voice if you prefer) "oooo noooo sorry, you really don't know what you're doing here do you, we're going to have to say no aren't we now.. ok?? ok."