Skip to content
Advertisement

Instantiate variables to None in Python

Why do these two blocks of code not do the same thing?

JavaScript

I wanted to “clean up” my code by doing the following, but it does not work the same as the code above.

JavaScript

Also is there a “cleaner” way to instantiate all the variables than the top block of code.

Advertisement

Answer

The other answers are great ways to more cleanly/efficiently set all the variables to None.

However, to answer this question:

Why do these two blocks of code not do the same thing?

The reason is, with your first line

JavaScript

you’re actually setting the variable at each index in the list equal to each of those variables. So, column_list[0] = category, column_list[1] = prodid_brand, etc.

Then with the next lines

JavaScript

you just changing the variable at each of those list indexes, and setting them to None (equivalent to column_list[0] = None).

Hence why none of your initial variables (category, prodid_brand, etc) are getting set, and you’re ending up with a list of six None values instead.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement