Python Variable Fundamentals Question

Asked 2 years ago, Updated 2 years ago, 24 views

Hello.

As I start without the basics of the program, the variables are blocked first.

I would like to do simple coding to monitor iPhone prices so that an alarm can be sent if there is a price change.

I declared each color as below, but an error occurs. 'IndexError: list assignment index out of range' I want to monitor the price of each color by declaring it as below and raising the i value one by one in the For statement, but the variable declaration is blocked. What's the reason? I've been googling a little bit, but I can't find a case like mine, so I'm posting a question here.

Color = []
Color[0] = "Grey"
Color[1] = "Gold"
Color[2] = "Midnight Green"
Color[3] = "Silver"

python

2022-09-21 11:53

1 Answers

The error message literally means that you have exceeded the scope of the index assigned to the list.
Python should not access unassigned indexes differently than languages such as JavaScript.

Workaround

Assign a new index using the append function. (Most recommended method)

color = []
color.append("Grey")
color.append("Gold")
color.append("Midnight Green")
color.append("Silver")

Initialize with None as much as you can use to declare list.

color = [None] * 4
color[0] = "Grey"
color[1] = "Gold"
color[2] = "Midnight Green"
color[3] = "Silver"

Use the dictionary.

color = {}
color[0] = "Grey"
color[1] = "Gold"
color[2] = "Midnight Green"
color[3] = "Silver"


2022-09-21 11:53

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.