0

I'm trying to set the index of an array in Python, but it isn't acting as expected:

theThing = []
theThing[0] = 0
'''Set theThing[0] to 0'''

This produces the following error:

Traceback (most recent call last):
  File "prog.py", line 2, in <module>
    theThing[0] = 0;
IndexError: list assignment index out of range

What would be the correct syntax for setting an index of an array in Python?

Anderson Green
  • 27,734
  • 61
  • 179
  • 311
  • Here it is on ideone, with the same error: http://ideone.com/0IV1Sc#view_edit_box – Anderson Green Apr 05 '13 at 02:00
  • `theThing = []` creates an empty array, so the index 0 doesn't exist. – Alex Gittemeier Apr 05 '13 at 02:01
  • 1
    I'm relatively unfamilar with Python (coming from a JavaScript background), so I found this to be surprising. In JavaScript, you can simply do `var theThing = new Array(); theThing[0] = 0;` to set the 0th element of `theThing` to 0. – Anderson Green Apr 05 '13 at 02:01
  • instead of `theThing[0]=0`, try `theThing.append(0)`. – Jakob Weisblat Apr 05 '13 at 02:06
  • It turns out that it's actually possible to initialize an array with a specific size in Python: http://stackoverflow.com/questions/6142689/initialising-an-array-of-fixed-size-in-python – Anderson Green Apr 05 '13 at 02:47
  • @AndersonGreen: Not really. `len(lst) == 5`. Also, if you replace `None` with a mutable object like a list in the accepted answer, things will not work the way you'd expect, as you're creating five references to the same object. – Blender Apr 05 '13 at 02:49

3 Answers3

5

Python lists don't have a fixed size . To set the 0th element, you need to have a 0th element:

>>> theThing = []
>>> theThing.append(12)
>>> theThing
[12]
>>> theThing[0] = 0
>>> theThing
[0]

JavaScript's array object works a bit differently than Python's, as it fills in previous values for you:

> x
[]
> x[3] = 5
5
> x
[undefined × 3, 5]
Blender
  • 275,078
  • 51
  • 420
  • 480
1

You're trying to assign to a non-existent position. If you want to add an element to the list, do

theThing.append(0)

If you really want to assign to index 0 then you must ensure the list is non-empty first.

theThing = [None]
theThing[0] = 0
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
1

It depends on what you really need. First you have to read python tutorials about list. In you case you can use smth like:

lVals = [] 
lVals.append(0)
>>>[0]
lVals.append(1)
>>>[0, 1]
lVals[0] = 10
>>>[10, 1]
Artsiom Rudzenka
  • 26,491
  • 4
  • 32
  • 51