In this article, we will learn all that you need to know about the variables in python.
In python, a variable is similar to a tag or reference that points to an object in the memory. For example,
x = 1
Here ‘1’ represents an integer object in the memory, and x is a reference or tag pointing to that object in memory.
Essential Points about a variable in python
- Unlike other programming languages ( C++ or Java ), in python, we don’t need to provide the type of information while defining a variable. Python implicitly assumes the type of the variable based on the value assigned to the variable.
- A variable in python is like a reference to an object in the memory.
Changing the value of a variable
We can force variable x to point to another object in the same program as this,
x = 1 x = 'sample'
Initially, x was pointing to an integer object, and now x is pointing to a string object in the memory. The type of the variable also changed, i.e., initially, it was an integer, but when we assigned a string object in it, then the type of x becomes str, i.e., a string.
If there is an object in memory, but no variable is pointing to that object, then it will be automatically freed by the garbage collector. Like in the above example, we forced the variable x to point to a string object, then int 1 was left in memory with no variable pointing toward it. Then the garbage collector freed the item automatically.
We can create assign a variable to another variable, for example,
y = x
Now both x & y variables are pointing to the same string object, i.e., ‘sample’. Let’s confirm this with an example,
x = 'sample' y = x print('x = ', x) print('y = ', y)
x = sample y = sample
A variable is an identifier in python, and there are specific rules which we need to keep in the mind while choosing a name for a variable in python. Check out the rules for naming a variable,
Rules for choosing a variable name in python
- A variable name can not start with a number like 2sample is an invalid name.
- A variable name can contain letters (a to z or A to Z), numbers (0 to 9), and underscore (_).
- For example: last_value, dataLoader, count_11 are some valid variable names.
- Keywords in python cannot be used as a variable name.
- Special symbols like !, @, #, $, %, etc. are not allowed as the variable name in python.
- There is no limitation on the length of a variable name in python.
- Variable names in python are case sensitive, i.e., ‘count’ and ‘Count’ are two different variable names in python.
- We should not use variable names that start and ends with two underscores like __len__. Python uses these kinds of terms to define special variables and methods inside the framework classes. We should avoid using this format to create new variables.
A variable in python is like a tag or reference pointing to an object in memory. We use this variable to access the value of the referred object in the code.
Thanks for reading.