Home > Mobile >  Naming a list with a number
Naming a list with a number

Time:11-27

Can you name a list with the first character being a number? I get an error when I try to do this. I am taking names of products and making lists and dictionaries with them and some of the names of the products start with a number. like:

11T25M = ["Grade", "Tensile", "Elongation"]

I get

11T25M = ["Grade", "Tensile", "Elongation"]
     ^
Syntax Error: invalid decimal literal

CodePudding user response:

No, you're not allowed to start a variable name with a number, regardless of the type of the variable (i.e. not just lists), the parser disallows it. This is fairly common amongst a lot of languages.

2e1 is a valid number in python (20), imagine if you wrote my_var = 2e1, is 2e1 a variable or a number? How is the parser to know?

Technically you could force a variable starting with a number for the name to exist through globals() but other than being terrible practice, it would be such a faff it's not worth the time or extra writing it would require.

CodePudding user response:

No you cannot start a variable name with a number. One solution is instead of having a bunch of variables, you can contain them all in a dictionary.

my_dict = {}
my_dict["11T25M"] = ["Grade", "Tensile", "Elongation"]
print(my_dict["11T25M"])

Now instead of having a list called 11T25M, you have a list called my_dict["11T25M"]

  • Related