Can anyone help?. Why does the code below outputs an error ? itm = [] itm [0] = "cat" print (itm) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone help?. Why does the code below outputs an error ? itm = [] itm [0] = "cat" print (itm)

Updating an empty list

13th Dec 2019, 5:55 AM
Charles Xstorm Ukadike
Charles Xstorm Ukadike - avatar
4 Answers
+ 2
The way you initialized this list, it has no slots available. It prints an error because itm[0] is not a place in the list yet. To add a slot to this list, use itm.append("cat"). Now you can also do itm[0] because its available in the list.
13th Dec 2019, 6:08 AM
coddy
coddy - avatar
+ 2
Thank you all for the quick response 👍
13th Dec 2019, 6:12 AM
Charles Xstorm Ukadike
Charles Xstorm Ukadike - avatar
+ 2
~ swim ~ I found out that itm.append("cat") and itm += "cat" aren't all that thesame. I checked with this code. words = ["hello", "world", "spam", "eggs"] itm = [] itm2 = [] for a in words : itm += a itm2.append(a) print (itm) print (itm2)
13th Dec 2019, 6:41 AM
Charles Xstorm Ukadike
Charles Xstorm Ukadike - avatar
- 2
<h1> </h1> <h2> </h2>
13th Dec 2019, 9:33 PM
Volodymyr Stesenko
Volodymyr Stesenko - avatar