1

Why does this work...

ASET = {}
ASET["X"] = "HELLO"
print(ASET)

But this not work...

ASET = []
ASET[0] = "HELLO"
print(ASET)

The first will result in:

{'X': 'HELLO'}

The second will generate the error:

 IndexError                                Traceback (most recent call last)
 <ipython-input-45-c521155a114d> in <module>
       1 ASET = []
 ----> 2 ASET[0] = "HELLO"
       3 print(ASET)

 IndexError: list assignment index out of range
Wasif
  • 14,755
  • 3
  • 14
  • 34
Will
  • 45
  • 1
  • 5
  • Does this answer your question? [Why does this iterative list-growing code give IndexError: list assignment index out of range?](https://stackoverflow.com/questions/5653533/why-does-this-iterative-list-growing-code-give-indexerror-list-assignment-index) – Gino Mempin Nov 01 '20 at 02:18
  • Doesn't answer your question, but there is a package for that https://github.com/carlosescri/DottedDict – SteveJ Nov 01 '20 at 02:29

1 Answers1

1

When you reference to an index in empty list, that index does not exist at that moment. To add values to a list (empty too) use .append():

ASET = []
ASET.append("HELLO")
print(ASET)

The other syntax can be used if you have something already at that index in list:

ASET = ['World']
ASET[0] = "HELLO"
print(ASET)
Wasif
  • 14,755
  • 3
  • 14
  • 34