Problem with lists | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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

27th Sep 2021, 1:09 PM
Brain & Bones
Brain & Bones - avatar
3 Antworten
+ 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.
27th Sep 2021, 1:43 PM
Simon Sauter
Simon Sauter - avatar
+ 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 :)
27th Sep 2021, 1:16 PM
Lisa
Lisa - avatar
+ 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..
27th Sep 2021, 1:28 PM
Jayakrishna 🇮🇳