+ 1
Problem with lists
I am struggling with this code. I am trying to add numbers to the list but the console is saying out of range. Please explain why this is happening and how to fix it. Thanks https://code.sololearn.com/cPM6v6Xq26C7/?ref=app
3 Respuestas
+ 4
You can add a new key-value pair to a dictionary like this:
d = {0:"a", 1:"b"}
d[2] = "c"
But you cannot add a new value to a list at a new index like this:
l = ["a", "b"]
l[2] = "c"
This way of assigning values to a list works only with an already existing index. So you can only replace a value like this, you cannot add one.
You can either use .append() to add a single value, .extend() to add an iterable or + to add a single value or a list.
+ 4
I would recommend using append() method for adding elements to a list
x = [0]
x.append(99)
Your code doesn't change list length :)
+ 4
initially Your list current max index is 1 only.. so line 5: sequence[len(sequence)] => sequence[2] will raise index error.
Use append method as noted above..