A variable is a name that refers to a value stored in memory. For example, if you want to store an employee’s salary, you can create a variable called salary and assign the amount to it. Later, you can use that variable name to read or change the salary.
Everything in Python is an object, so a variable is really a label (reference) attached to an object. The value it refers to can change as your program runs, for example, based on a condition or on user input. That’s why it’s called a variable.
The object a variable refers to can be either mutable or immutable. A mutable object (such as a list) can be changed in place, while an immutable object (such as an integer or a string) cannot. You’ll learn the difference later in this article.
Table of contents
- Creating a variable
- Changing the value of a variable
- Create number, string, and list variables
- Get the data type of a variable
- Convert a variable to another type
- Print variables with f-strings
- Delete a variable
- Variables are case-sensitive
- Constant
- Rules and naming convention for variables and constants
- Multiple assignments
- Variable scope
- Object/variable identity and references
- Mutable and immutable objects
- Unpack a collection into variables
- Summary
Creating a variable
Python is dynamically typed, so you don’t need to declare a variable or its data type before using it, as you do in languages like C or Java. A variable is created automatically the first time you assign a value to it.
Creating a variable and assigning a value
Use the assignment operator = to assign a value to a variable. The name on the left side of = is the variable name, and the expression on the right side is the value.
variable_name = variable_valueCode language: Python (python)
Example
In this example, “John”, 25, and 25800.60 are assigned to the variables name, age, and salary, respectively.
Type hints (optional): You can add a type annotation to show what kind of value a variable should hold, for example, price: float = 9.99. Python doesn’t enforce it, but editors and tools use it to catch mistakes.
Changing the value of a variable
Many programming languages are statically typed: a variable is declared with a specific type and must keep that type for its whole lifetime.
Python variables are dynamically typed and are not tied to a data type. You can assign a value of one type to a variable and later reassign it to a value of a different type.
Example
Create number, string, and list variables
You can create variables of different types depending on what you need to store. Let’s look at the most common ones.
Number
Numbers are data types that store numeric values. Python creates the number object when you assign the value to a variable. Python 3 has three numeric types:
intfloatcomplex
Integer variable
The int type stores whole numbers, also called integers. They can be positive or negative and have no decimal point. Python integers have no size limit.
Example
Note: We used the built-in type() function to check the variable’s type.
Float variable
Floats are numbers with a decimal point separating the whole and fractional parts. Use the float type to store decimal values.
Example
In this example, the variable salary is assigned the value 10800.55, which is a float.
Complex type
A complex number has a real part and an imaginary part. It is written in the form a + bj, where a and b are integers or floats and j represents the imaginary unit.
Example
String variable
In Python, a string is a sequence of characters enclosed in quotation marks. You can use either single or double quotes. For example, use a string to store a person’s name.
To get a single character, use indexing with []. To get a part of a string, use the slice operator [start:end], which returns the characters from index start up to, but not including, index end. Indexes start at 0.
To join (concatenate) strings, use the addition (+) operator.
Example
Tip: Don’t name a variable str, list, or type. Those names already belong to built-in functions, and reusing them hides the built-in.
List type variable
Use a list when you want to store a group of values as a single entity, for example, a list of student names.
Read: Complete guide on Python lists
You can access list items using a positive index (counting from the start) or a negative index (counting from the end). Lists have the following characteristics:
- The insertion order of items is preserved.
- Items can be of different types (
int,float,str, and so on). - Duplicate items are allowed.
- Lists are mutable: you can change their items.
- Lists can grow and shrink as needed.
- List items are enclosed in square brackets
[].
Example
Boolean and None
A bool variable holds one of two values, True or False. It is often the result of a comparison. The special value None means “no value” and is often used as a placeholder.
Get the data type of a variable
A variable can refer to a value of any type, such as int, float, str, list, tuple, or dict. To find out the type of the value a variable currently holds, use the built-in type() function.
Syntax of type():
type(variable_name)Code language: Python (python)
Example
If you only want the name of the type, use the __name__ attribute of the result:
Example
To check whether a variable is of a certain type, use isinstance(), for example, isinstance(a, int) returns True.
Convert a variable to another type
You can convert (cast) a value to another type with the built-in functions int(), float(), str(), list(), and so on. This is common when you read input from the user, because input() always returns a string.
Print variables with f-strings
An f-string (a string prefixed with f) lets you put variables directly inside text using curly braces. It is the easiest way to display variables in a message.
Delete a variable
Use the del keyword to delete a variable. After you delete it, the name is no longer accessible. If no other variable refers to the same object, Python’s garbage collector frees its memory.
Example
Now, let’s delete var1 and try to access it again.
Example
Output:
NameError: name 'var1' is not defined
Variables are case-sensitive
Python is a case-sensitive language. If you define a = 100 and A = 200, Python treats a and A as two different variables.
Example
Constant
A constant is a value that should not change while the program runs. Python has no built-in way to make a variable truly constant. Instead, by convention, you write constant names in all uppercase letters to tell other programmers not to change them.
Example
This is only a convention: Python still lets you change the value of MAX_VALUE. If you use a type checker, you can mark a name with typing.Final (for example, MAX_VALUE: Final = 500) so the checker reports any reassignment.
Assigning a value to a constant in Python
A common practice is to keep all constants together in a separate module. A module is simply a Python file (.py) that contains variables, functions, or classes.
Let’s create two modules, constant.py and main.py:
- In
constant.py, declare two constants,PIandTOTAL_AREA. - In
main.py, import theconstantmodule and use them.
Write the following code in the constant.py file:
PI = 3.14
TOTAL_AREA = 205Code language: Python (python)
Constant names use uppercase letters, with words separated by underscores.
Now create main.py and write the following code in it:
Example
import constant
print(constant.PI)
print(constant.TOTAL_AREA)Code language: Python (python)
Output
3.14 205
Note: Writing names in uppercase marks them as constants, but it doesn’t prevent reassignment.
Rules and naming convention for variables and constants
A name in a Python program is called an identifier. Variable names, function names, class names, and module names are all identifiers. Follow these rules and conventions when naming variables and constants.
Rule 1: A name can contain only letters, digits, and underscores:
- Letters: lowercase (a to z) or uppercase (A to Z)
- Digits (0 to 9)
- Underscore (_)
Example
total_addition
TOTAL_ADDITION
totalAddition
TotaladditionCode language: Python (python)
Rule 2: A name can’t start with a digit.
1student = "Jessa" # SyntaxError
student_1 = "Jessa" # validCode language: Python (python)
Rule 3: Don’t use special symbols such as $, #, @, %, !, or ~ in a name. Python raises a syntax error if you do.
Example
Output
ca$h = 1000
^
SyntaxError: invalid syntax
Rule 4: Don’t use Python keywords such as if, for, class, or True as names. They are reserved for the language itself.
Rule 5: Names are case-sensitive.
Output
120 130 150
Python treats uppercase and lowercase letters as different, so it creates three separate variables: total, Total, and TOTAL.
Convention 1: Choose meaningful names that describe the value.
x = "Jessa" # unclear
student_name = "Jessa" # meaningfulCode language: Python (python)
Convention 2: Use lowercase words separated by underscores for variable names (this style is called snake_case).
current_temperature = 24Code language: Python (python)
Convention 3: Use uppercase letters with underscores for constants.
MIN_VALUE = 100
MAX_VALUE = 1000Code language: Python (python)
Multiple assignments
Python lets you assign values to several variables in a single statement. There are two ways to do this: assign a single value to multiple variables, or assign multiple values to multiple variables.
Assigning a single value to multiple variables
You can chain the assignment operator = to give several variables the same value at once. Here, all three variables a, b, and c get the value 10.
Example
Assigning multiple values to multiple variables
Example:
Here, the integers 10 and 70 are assigned to roll_no and marks, and the string “Jessa” is assigned to name.
This also gives you an easy way to swap two variables without a temporary variable:
Variable scope
The scope of a variable is the part of the program where you can access it.
Depending on their scope, variables fall into two main types: local variables and global variables.
Local variable
A local variable is created inside a function and can only be used inside that function. If you try to access it from outside the function, you get an error.
Example
Here, we created a local variable price inside the function test1(). In test2(), we tried to access price, but we got the error name 'price' is not defined, because its scope is limited to test1().
Global variable
A global variable is defined outside of any function, at the top level of the file. It can be read from anywhere in that file, including inside functions.
Example
Both functions print the same value because the global variable is accessible throughout the file.
Note: A function can read a global variable, but to change it inside a function, you must declare it with the global keyword. Otherwise, Python creates a new local variable instead.
Object/variable identity and references
Whenever Python creates an object, it gives the object a unique number called its identity. In CPython (the standard Python implementation), this number is the object’s memory address. An object’s identity never changes during its lifetime, and no two objects that exist at the same time share the same identity. The built-in id() function returns it.
Think of a library: the books are memory locations, and the students are objects. When a new student arrives (a new object is created), the librarian gives them a book with a unique number (the identity). That number tells you exactly which book belongs to which student.
Example
Both lines print the same address because m = n doesn’t copy the value. It makes m refer to the same object as n. The is operator checks whether two variables refer to the same object. If you later assign a different value to m, it refers to a different object with a different identity.
For m = 500, Python creates an integer object with the value 500 and makes m refer to it. Similarly, n refers to an integer object with the value 400. The two variables have different identities. (The exact numbers will differ on your computer.)
Object reference
When you assign a value to a variable, Python creates (or reuses) an object and makes the variable refer to it.
For example, with a = 10, an object with the value 10 is stored in memory, and the name a points to it.
For efficiency, CPython keeps a single shared object for each small integer (from -5 to 256) and for many short strings. So if you write a = 10 and b = 10, both names refer to the same object instead of two separate ones. This is an internal optimization: don’t rely on it for larger numbers, and always compare values with == rather than is.
Example
Output (addresses will differ on your computer)
140722211837248 140722211837248 140722211837568 140722211837568 140722211837568
a and b refer to the same object with the value 10, and c, d, and e all refer to the same object with the value 20.
Python keeps track of how many references point to each object (its reference count). When the count drops to zero, the object’s memory is freed. You can check the count with sys.getrefcount():
The numbers you see will usually be larger than you expect, because Python itself (and the call to getrefcount()) also hold references to these shared objects.

In the image above, a and b point to the same memory location, and c, d, and e point to another shared location.
Mutable and immutable objects
- Immutable objects can’t be changed after they are created:
int,float,bool,str,tuple, andfrozenset. “Changing” one actually creates a new object. - Mutable objects can be changed in place:
list,dict, andset.
This matters when two variables refer to the same object:
Because b = a doesn’t copy the list, changing it through b also changes what a sees. To get an independent copy, use b = a.copy().
Unpack a collection into variables
Packing
- You can create a tuple by packing several values into a single variable.
- This is called tuple packing, and it is useful when you want to collect multiple values in one variable.
Example
Here, a, b, c, and d are packed into the tuple tuple1.
Tuple unpacking is the reverse of packing. It assigns the values of a tuple (or any sequence) to separate variables.
Example
Note: When unpacking, the number of variables on the left must match the number of values on the right. Otherwise, you get a ValueError.
Example
Output
a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2)
To collect “the rest” of the values, put an asterisk (*) before one variable name. That variable receives a list of the remaining values:
Summary
- A variable is a name that refers to an object. It is created the first time you assign a value with
=. - Python is dynamically typed: a variable can refer to values of different types over time. Use
type()orisinstance()to check the type. - Convert between types with
int(),float(),str(), and similar functions. - Names can contain letters, digits, and underscores, can’t start with a digit, can’t be keywords, and are case-sensitive. Use snake_case for variables and UPPER_CASE for constants.
- Local variables live inside a function. Global variables live at the top level of a file, and you need the
globalkeyword to change them inside a function. - Assigning one variable to another shares the same object. This matters for mutable objects such as lists.
- Use packing and unpacking (including
*rest) to work with several values at once.
Also, See:
