-3

I am using below code for adding an element in array but it is giving me below error while running it

cars = ["Ford", "Volvo", "BMW"] 
cars.append("Honda") 
cars[4] = "BMWq";
for x in cars:
  print(x) 

Output error

List assignment index out of range

Not able to understand reason of this error

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44

1 Answers1

2

You can't extend a Python list by assigning values to an element that doesn't exist. This

cars.append("Honda") 

is the correct way to assign a new element 3. To assign element 4 that does not yet exist, call cars.append() again.

BoarGules
  • 16,440
  • 2
  • 27
  • 44