A variable is a reserved memory area (memory address) to store value. For example, we want to store an employee’s salary. In such a case, we can create a variable and store salary using it. Using that variable name, you can read or modify the salary amount.
In other words, a variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python.
A variable can be either mutable or immutable. If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable. We will learn the difference between mutable and immutable types in the later section of this article.
Table of contents
- Creating a variable
- Changing the value of a variable
- Create Number, String, List variables
- Get the data type of variable
- Delete a variable
- Variable’s case-sensitive
- Constant
- Rules and naming convention for variables and constants
- Multiple assignments
- Variable scope
- Object/Variable identity and references
- Unpack a collection into a variable
Creating a variable
Python programming language is dynamically typed, so there is no need to declare a variable before using it or declare the data type of variable like in other programming languages. The declaration happens automatically when we assign a value to the variable.
Creating a variable and assigning a value
We can assign a value to the variable at that time variable is created. We can use the assignment operator =
to assign a value to a variable.
The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value.
<code>variable_name = variable_value</code>
Code language: Python (python)
Example
In the above example, “John”, 25, 25800.60 are values that are assigned to name
, age
, and salary
respectively.
Changing the value of a variable
Many programming languages are statically typed languages where the variable is initially declared with a specific type, and during its lifetime, it must always have that type.
But in Python, variables are dynamically typed and not subject to the data type restriction. A variable may be assigned to a value of one type, and then later, we can also re-assigned a value of a different type. Let’s see the example.
Example
Create Number, String, List variables
We can create different types of variables as per our requirements. Let’s see each one by one.
Number
A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values.
- Int
- float
- complex
Integer variable
The int
is a data type that returns integer type values (signed integers); they are also called ints or integers. The integer value can be positive or negative without a decimal point.
Example
Note: We used the built-in Python method type()
to check the variable type.
Float variable
Floats are the values with the decimal point dividing the integer and the fractional parts of the number. Use float data type to store decimal values.
Example
In the above example, the variable salary assigned to value 10800.55, which is a float
value.
Complex type
The complex
is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values.
Example
String variable
In Python, a string is a set of characters represented in quotation marks. Python allows us to define a string in either pair of single or double quotation marks. For example, to store a person’s name we can use a string type.
To retrieve a piece of string from a given string, we can use to slice operator []
or [:]
. Slicing provides us the subset of a string with an index starting from index 0 to index end-1.
To concatenate the string, we can use the addition(+)
operator.
Example
List type variable
If we want to represent a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact.
Read: Complete Guide on Python lists
The list can be accessed in two ways, either positive or negative index. The list has the following characteristics:
- In the list insertion order of elements is preserved.
- Heterogeneous (all types of data types
int
,float
,string
) elements are allowed. - Duplicates elements are permitted.
- The list is mutable(can change).
- Growable in nature means based on our requirement, we can increase or decrease the list’s size.
- List elements should be enclosed within square brackets
[]
.
Example
Get the data type of variable
No matter what is stored in a variable (object), a variable can be any type like int
, float
, str
, list
, tuple
, dict
, etc. There is a built-in function called type()
to get the data type of any variable.
The type()
function has a simple and straightforward syntax.
Syntax of type()
:
type(<variable_name>)
Code language: Python (python)
Example
If we want to get the name of the datatype only as output, then we can use the__name__
attribute along with the type()
function. See the following example where __name__
attribute is used.
Example
Delete a variable
Use the del
keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector.
Example
Now, let’s delete var1
and try to access it again.
Example
Output:
NameError: name 'var1' is not defined
Variable’s case-sensitive
Python is a case-sensitive language. If we define a variable with names a = 100
and A =200
then, Python differentiates between a
and A
. These variables are treated as two different variables (or objects).
Example
Constant
Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is not applicable. By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it.
Example
MAX_VALUE = 500
Code language: Python (python)
It is just convention, but we can change the value of MAX_VALUE
variable.
Assigning a value to a constant in Python
As we see earlier, in the case of Python, the constant concept is not applicable. But if we still want to implement it, we can do it using the following way.
The declaration and assignment of constant in Python done with the module. Module means Python file (.py
) which contains variables, functions, and packages.
So let’s create two modules, constant.py
and main.py
, respectively.
- In the
constant.py
file, we will declare two constant variables,PI
andTOTAL_AREA
. - import constant module In
main.py
file.
To create a constant module write the below code in the constant.py
file.
PI = 3.14
TOTAL_AREA = 205
Code language: Python (python)
Constants are declared with uppercase later variables and separating the words with an underscore.
Create a main.py and write the below code in it.
Example
import constant
print(constant.PI)
print(constant.TOTAL_AREA)
Code language: Python (python)
Output
3.14 205
Note: Constant concept is not available in Python. By convention, we define constants in an uppercase letter to differentiate from variables. But it does not prevent reassignment, which means we can change the value of a constant variable.
Rules and naming convention for variables and constants
A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name.
There are some rules to define variables in Python.
In Python, there are some conventions and rules to define variables and constants that should follow.
Rule 1: The name of the variable and constant should have a combination of letters, digits, and underscore symbols.
- Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z)
- Digits(0 to 9)
- Underscore symbol (_)
Example
total_addition
TOTAL_ADDITION
totalAddition
Totaladdition
Code language: Python (python)
Rule 2: The variable name and constant name should make sense.
Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful.
Example
x = "Jessa"
student_name = "Jessa"
Code language: Python (python)
It above example variable x
does not make more sense, but student_name
is a meaningful variable.
Rule 3: Don’t’ use special symbols in a variable name
For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error
Example
Output
ca$h = 11 ^ SyntaxError: invalid syntax
Rule 4: Variable and constant should not start with digit letters.
You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example.
1studnet = "Jessa"
print(1studnet)
Code language: Python (python)
Here Python will generate a syntax error at 1studnet
. instead of this, you can declare a variable like studnet_1 = "Jessa"
Rule 5: Identifiers are case sensitive.
Output
120 130 150
Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables total
, Total
, TOTAL
.
Rule 6: To declare constant should use capital letters.
MIN_VALUE = 100
MAX_VALUE = 1000
Code language: Python (python)
Rule 6: Use an underscore symbol for separating the words in a variable name
If we want to declare variable and constant names having two words, use an underscore symbol for separating the words.
current_temperature = 24
Code language: Python (python)
Multiple assignments
In Python, there is no restriction to declare a variable before using it in the program. Python allows us to create a variable as and when required.
We can do multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables.
Assigning a single value to multiple variables
we can assign a single value to multiple variables simultaneously using the assignment operator =
.
Now, let’s create an example to assign the single value 10
to all three variables a
, b
, and c
.
Example
Assigning multiple values to multiple variables
Example:
In the above example, two integer values 10 and 70 are assigned to variables roll_no
and marks
, respectively, and string literal, “Jessa,” is assigned to the variable name
.
Variable scope
Scope: The scope of a variable refers to the places where we can access a variable.
Depending on the scope, the variable can categorize into two types local variable and the global variable.
Local variable
A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error.
Example
In the above example, we created a function with the name test1
. Inside it, we created a local variable price. Similarly, we created another function with the name test2
and tried to access price, but we got an error "price is not defined"
because its scope is limited to function test1()
. This error occurs because we cannot access the local variable from outside the code block.
Global variable
A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.
Example
In the above example, we created a global variable price and tried to access it in test1
and test2
. In return, we got the same value because the global variable is accessible in the entire file.
Note: You must declare the global variable outside function.
Object/Variable identity and references
In Python, whenever we create an object, a number is given to it and uniquely identifies it. This number is nothing but a memory address of a variable’s value. Once the object is created, the identity of that object never changes.
No two objects will have the same identifier. The Object is for eligible garbage collection when deleted. Python has a built-in function id()
to get the memory address of a variable.
For example, consider a library with many books (memory addresses) and many students (objects). At the beginning(when we start The Python program), all books are available. When a new student comes to the library (a new object created), the librarian gives him a book. Every book has a unique number (identity), and that id number tells us which book is delivered to the student (object)
Example
It returns the same address location because both variables share the same value. But if we assign m
to some different value, it points to a different object with a different identity.
See the following example
For m = 500
, Python created an integer object with the value 500 and set m
as a reference to it. Similarly, n
is assigned to an integer object with the value 400
and sets n as a reference to it. Both variables have different identities.
Object Reference
In Python, when we assign a value to a variable, we create an object and reference it.
For example, a=10
, here, an object with the value 10
is created in memory, and reference a
now points to the memory address where the object is stored.
Suppose we created a=10
, b=10
, and c=10
, the value of the three variables is the same. Instead of creating three objects, Python creates only one object as 10
with references such as a
,b
,c
.
We can access the memory addresses of these variables using the id()
method. a
, b
refers to the same address in memory, and c
, d
, e
refers to the same address. See the following example for more details.
Example
Output
140722211837248 140722211837248 140722211837568 140722211837568 140722211837568
Here, an object in memory initialized with the value 10 and reference added to it, the reference count increments by ‘1’.
When Python executes the next statement that is b=10
, since it is the same value 10, a new object will not be created because the same object in memory with value 10 available, so it has created another reference, b
. Now, the reference count for value 10 is ‘2’.
Again for c=20
, a new object is created with reference ‘c’ since it has a unique value (20). Similarly, for d
, and e
new objects will not be created because the object ’20’ already available. Now, only the reference count will be incremented.
We can check the reference counts of every object by using the getrefcount
function of a sys
module. This function takes the object as an input and returns the number of references.
We can pass variable, name, value, function, class as an input to getrefcount()
and in return, it will give a reference count for a given object.
See the following image for more details.

In the above picture, a
, b
pointing to the same memory address location (i.e., 140722211837248), and c
, d
, e
pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2 and 3 respectively.
Unpack a collection into a variable
Packing
- In Python, we can create a tuple (or list) by packing a group of variables.
- Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing.
Example
Here a
, b
, c
, d
are packed in the tuple tuple1
.
Tuple unpacking is the reverse operation of tuple packing. We can unpack tuple and assign tuple values to different variables.
Example
Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError.
Example
Output
a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2)
Also, See: