mylist = ["a", "apple", "b", "ball", "c", "cat"]
mylist[6] = "value"
print(mylist)
Error:
IndexError: list assignment index out of range
I remember assigning values by index in javascript, it doesn't work in python?
mylist = ["a", "apple", "b", "ball", "c", "cat"]
mylist[6] = "value"
print(mylist)
Error:
IndexError: list assignment index out of range
I remember assigning values by index in javascript, it doesn't work in python?
Python's lists are 0-indexed. You have 6 elements in your list, so you can index them with anything from 0 to 5. Attempting to go beyond those bounds will not work with the normal list type, but it seems you want to use indexing as implicit list-extension.
For that you want a sparse container, and here's a quick implementation that subclasses list.
class SparseList(list):
def __setitem__(self, index, value):
"""Overrides list's __setitem__ to extend the list
if the accessed index is out of bounds."""
sparsity = index - len(self) + 1
self.extend([None] * sparsity)
list.__setitem__(self, index, value)
Use this like this:
In [8]: sl = SparseList()
In [9]: print(sl)
[]
In [10]: sl[3] = "hi"
In [11]: print(sl)
[None, None, None, 'hi']
And your specific example:
In [11]: mylist = SparseList(["a", "apple", "b", "ball", "c", "cat"])
In [12]: print mylist
['a', 'apple', 'b', 'ball', 'c', 'cat']
In [13]: mylist[6] = "value"
In [14]: print mylist
['a', 'apple', 'b', 'ball', 'c', 'cat', 'value']
And if you want something a little less self-made, try blist
In python single assignment does not work if the index does not exist. Javascript arrays are "sparse", you can stash a value at any index. Instead, python lists have a defined size, and assignment is only allowed in existing indices.
If you want to add at the end, use mylist.append(value),
What you are asking can be done with SparseList as described by birrye. Or you can always use append. In python dictionary though you can have any indexed assignment say,
dic = {}
dic['1'] = 100
dic['2'] = 200
So what you can do is write like this,
list = {}
i = 1 #Your index
list[str(i)] = value #Your value
This might increase the execution time a bit. You will get IndexError exception raised if you reference any unassigned index.
You can achieve this by first creating a list of None objects, but it's probably not the best way to do things.
mylist = [None] * 10
mylist[0:5] = ["a", "apple", "b", "ball", "c", "cat"]
mylist[6] = "value"
Alternatively, you could just append elements to the end of the list.
mylist = ["a", "apple", "b", "ball", "c", "cat"]
# create 7th element
mylist += ["value"]
# create 10th element
mylist += [None] * 2 + ["value2"]