Anderson Green
Anderson Green

Reputation: 31850

Set the index of a Python array

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?

Upvotes: 2

Views: 8574

Answers (3)

Blender
Blender

Reputation: 298532

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]

Upvotes: 5

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

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]

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362107

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

Upvotes: 1

Related Questions