For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
When you start learning Python, one of the first concepts you'll come across is python variables. Think of a variable as a labeled storage box for your data. Whether you're storing a user's name, the result of a calculation, or even a complex dataset, python variables help you keep that information handy and organized.
But here's the thing — python variables are more than just containers. They’re dynamic, flexible, and incredibly easy to use, which is one of the many reasons Python is loved by beginners and pros alike. Also, it’s a must to learn concept to become a pro level python developer.
In this blog, we’ll walk through everything you need to know about python variables, including what they are, how they work, how to use them effectively, and some of the neat tricks you can do with them. Whether you’re just getting started or brushing up your skills, this guide will make sure you’ve got a solid grip on the foundation of working with python variable types. Also, it’ll help you go through any of the next-gen software development course.
At its core, a python variable is simply a name that refers to a value. When you assign a value to a python variable, Python creates an object in memory and binds that name to the object. This makes working with data seamless and intuitive.
In addition, also know about the advantages of Python to strengthen your foundational knowledge.
In Python, you don’t need to declare the type of a variable. Just assign a value and Python figures it out for you based on the data.
Here's a basic example:
# Assigning a string value to a python variable
name = "Alice"
# Assigning an integer to another python variable
age = 30
# Assigning a floating-point number
height = 5.6
# Output the variables
print(name) # Output: Alice
print(age) # Output: 30
print(height) # Output: 5.6
Explanation:
In this example, we’ve created three python variables: `name`, `age`, and `height`. Each one is storing a different type of value — a string, an integer, and a float respectively. Python automatically identifies the type based on the assigned value.
Consistently Advance Your Career with the following Full-stack Development Courses:
While python variables are dynamically typed, the data they hold can be categorized into several standard types. Here are some of the most commonly used variable types:
Type | Description | Example |
str | Stores text data (strings) | "Hello, World!" |
int | Stores whole numbers | 42 |
float | Stores decimal numbers | 3.14 |
bool | Stores boolean values (True or False) | True, False |
list | Ordered, changeable collection of items | [1, 2, 3, "apple"] |
tuple | Ordered, unchangeable collection of items | (10, 20, 30) |
dict | Stores data in key-value pairs | {"name": "Alice", "age": 30} |
set | Unordered collection of unique items | {1, 2, 3} |
For more in-depth details, explore our article on Data Types in Python.
Following rules must be followed by using python variables in your programs:
Also read our article on Operators in Python fore more detailed understanding.
In Python, assigning values to python variables is simple. You use the `=` operator, and Python automatically identifies the type of the variable based on the assigned value.
# Assigning different types of values to python variables
name = "Alice" # string
age = 25 # integer
height = 5.7 # float
is_student = True # boolean
print(name)
print(age)
print(height)
print(is_student)
Output:
Alice
25
5.7
True
Explanation:
Each python variable holds a different type of data. Python automatically detects the data type based on the value.
You can reassign a new value (even of a different type) to a python variable.
# Reassigning a python variable to a new value and type
count = 10 # Initially an integer
count = "Ten" # Now a string
print(count)
Output:
Ten
Explanation:
The python variable `count` was initially an integer but was reassigned to a string. Python allows such reassignment without issues.
Explore Python Frameworks article to gain advance-level insights.
You can assign the same value to multiple python variables in one line.
# Assigning the same value to multiple python variables
x = y = z = 100
# Output the values of each variable
print(x)
print(y)
print(z)
Output:
100
100
100
Explanation:
In this case, the value `100` is assigned to three different python variables (`x`, `y`, and `z`) in a single line.
In Python, you can assign multiple variables in a single line, either with the same or different values. This can help make your code cleaner and more concise.
You can assign different values to multiple python variables on the same line, using a comma to separate the variable names and values.
# Assigning different values to multiple python variables
a, b, c = 10, 20, 30
# Output the assigned values
print(a) # Output: 10
print(b) # Output: 20
print(c) # Output: 30
Output:
10
20
30
Explanation:
In this example, the values `10`, `20`, and `30` are assigned to the variables `a`, `b`, and `c` respectively in a single line.
You can also assign the same value to multiple python variables in a single line.
# Assigning the same value to multiple python variables
x = y = z = 50
# Output the assigned values
print(x) # Output: 50
print(y) # Output: 50
print(z) # Output: 50
Output:
50
50
50
Explanation:
Here, the value `50` is assigned to three different variables (`x`, `y`, and `z`) in a single line.
Python allows you to swap the values of two variables without needing a temporary variable.
# Swapping values between two python variables
a, b = 10, 20
a, b = b, a # Swapping values
# Output the swapped values
print(a) # Output: 20
print(b) # Output: 10
Output:
20
10
Explanation:
The values of `a` and `b` are swapped in one line using Python's built-in tuple unpacking feature.
In Python, type casting refers to the conversion of a python variable from one data type to another. This is especially useful when you need to perform operations between different types of data or handle user inputs.
Python automatically converts smaller data types to larger ones when required. This is known as implicit type casting.
# Implicit type casting example
a = 5 # Integer
b = 3.2 # Float
result = a + b # Python automatically converts 'a' to float before performing the operation
print(result)
Output:
8.2
Explanation:
In this example, Python automatically converts the integer `a` into a float to perform the addition with the float `b`.
Sometimes, you may want to manually convert a variable from one type to another. This is called explicit type casting, which is done using the built-in functions such as `int()`, `float()`, `str()`, etc.
# Explicit type casting examples
x = "123" # String
y = int(x) # Converting string to integer
z = float(y) # Converting integer to float
print(y)
print(z)
Output:
123
123.0
Explanation:
Here, the string `x` is first converted to an integer using `int()`, and then the integer is converted to a float using `float()`.
When you receive user input, it’s always in the form of a string. You often need to convert it to other types like integers or floats.
# Taking user input and converting it
user_input = input("Enter a number: ") # Input is always a string
num = int(user_input) # Converting the string to an integer
# Output the converted value
print(num)
Example Output:
Enter a number: 42
42
Explanation:
The `input()` function returns a string, and we convert it to an integer using `int()` before performing any operations on it.
In Python, it’s often useful to check the type of a python variable to ensure it holds the expected value type. Python provides the built-in `type()` function for this purpose, which returns the class type of the variable.
You can use the `type()` function to determine the type of any python variable. It helps in debugging and understanding your data.
# Checking the type of different python variables
name = "Alice" # string
age = 25 # integer
height = 5.7 # float
is_active = True # boolean
# Output the types
print(type(name))
print(type(age))
print(type(height))
print(type(is_active))
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
Explanation:
The `type()` function is used to print the class type of each python variable. For example, `name` is a string, `age` is an integer, etc.
In addition, explore article on slicing in Python to do more with string data type in your applications.
It’s a good practice to check variable types before performing certain operations, especially if you're working with user inputs or dynamic data.
# Checking the type before performing arithmetic operation
x = 10 # Integer
y = "5" # String
# Check types before adding
if isinstance(y, int):
result = x + y
else:
print("Cannot add integer and string!")
Output:
Cannot add integer and string!
Explanation:
In this example, we used `isinstance()` to ensure that `y` is an integer before trying to add it to `x`. Since `y` is a string, the addition operation is prevented.
In Python, the scope of a variable defines where it can be accessed in your code. The two most important types of scope are local and global.
A python variable has a local scope if it is defined within a function. This means that the variable is only accessible inside that function.
def my_function():
local_var = "I am local" # Local variable
print(local_var) # Accessible inside the function
my_function()
Output:
I am local
Explanation:
In this example, `local_var` is defined inside `my_function()`. It is accessible only within the function and cannot be used outside of it.
A python variable has a global scope if it is defined outside any function. A global variable is accessible throughout the entire script or module, including inside functions. For more details, read about our article on global variable in Python.
global_var = "I am global" # Global variable
def my_function():
print(global_var) # Accessible inside the function
my_function()
Output:
I am global
Explanation:
In this case, `global_var` is defined outside the function and is accessible both inside and outside the function, as it has global scope.
In Python, variables don’t store data directly. Instead, they store references to objects in memory. This means when you assign a variable to another, both variables refer to the same object in memory. This is important to understand when working with mutable and immutable objects.
Also, it’s recommended to learn about memory management in Python for better understanding.
When a python variable is assigned a value, it doesn't directly store the value. Instead, it stores a reference to the object that contains the value.
a = [1, 2, 3] # List assignment
b = a # b refers to the same object as a
# Modify the object using b
b.append(4)
print(a)
print(b)
Output:
[1, 2, 3, 4]
[1, 2, 3, 4]
Explanation:
In this example, `a` and `b` both refer to the same list in memory. When the list is modified through `b`, the change is reflected in `a` as well. This happens because both variables are referencing the same object.
Python objects can be either mutable (can be changed after creation) or immutable (cannot be changed after creation). Lists are mutable, while strings are immutable.
Mutable Objects (e.g., List)
When working with mutable objects, both variables that refer to the same object will be affected by changes made to the object.
x = [10, 20, 30] # Mutable object (list)
y = x # y refers to the same object as x
x.append(40) # Modify the list through x
print(x)
print(y)
Output:
[10, 20, 30, 40]
[10, 20, 30, 40]
Explanation:
Both `x` and `y` refer to the same list object. When the list is modified via `x`, the change is reflected in `y`.
Immutable Objects (e.g., String)
For immutable objects, modifying one variable will not affect the other, because a new object is created instead of modifying the original object.
a = "hello" # Immutable object (string)
b = a # b refers to the same object as a
a = "world" # Reassign a to a new string object
print(a)
print(b)
Output:
world
hello
Explanation:
Strings are immutable. When `a` is reassigned to a new string, `b` remains unchanged, as it still refers to the original string `"hello"`.
In Python, variables can be deleted using the `del` keyword. This keyword removes a variable or an object from memory, making it inaccessible for further use. It is useful when you want to clean up memory or remove references to objects that are no longer needed.
You can delete a single python variable by using the `del` keyword followed by the variable name.
x = 10 # Assigning a value to a variable
del x # Deleting the variable
# Trying to access x after deletion will raise an error
# print(x) # This will raise a NameError: name 'x' is not defined
Explanation:
The `del` keyword deletes the variable `x` from memory. After deletion, if you attempt to access `x`, Python will raise a `NameError` because the variable no longer exists.
Also read about list methods in Python to gain pro-level development insights.
You can also use `del` to remove an element from a list by specifying its index.
my_list = [1, 2, 3, 4, 5]
# Deleting the element at index 2 (the number 3)
del my_list[2]
print(my_list)
Output:
[1, 2, 4, 5]
Explanation:
In this case, `del` removes the element at index 2 of `my_list` (the value `3`), and the list is updated accordingly.
You can also delete multiple variables at once by passing them as a comma-separated list.
a = 10
b = 20
c = 30
# Deleting multiple variables
del a, b, c
# Trying to access any of these variables will raise an error
# print(a) # This will raise a NameError
Explanation:
The `del` statement deletes multiple variables at once. After deletion, attempting to access any of the deleted variables will result in a `NameError` since they are no longer defined.
Explore our must read article on Speech recognition in Python develop cutting-edge application.
Python variables are key to understanding how data is stored and manipulated within your programs. Whether dealing with local or global scopes, knowing where and how variables are accessible is crucial for managing the flow of your code. Additionally, understanding the concept of object references helps you grasp the behavior of mutable and immutable objects and how changes to one variable can affect others. By leveraging Python’s del keyword, you can clean up your code by deleting variables and freeing up memory when they are no longer needed.
In summary, mastering Python variables allows you to write cleaner, more efficient code. By knowing when and how to use type casting, handle variable scopes, and delete unused variables, you can improve the maintainability and performance of your Python applications. As you continue coding, these foundational concepts will help you create more organized and bug-free programs.
Python variables don’t directly store values. Instead, they are labels attached to objects in memory. When a variable is created, Python automatically manages the memory allocation and garbage collection. Variables are names pointing to memory locations where objects are stored, and Python's memory management handles the object's lifecycle.
Python is a dynamically typed language, meaning the type of a variable is determined at runtime, not in advance. This allows for more flexibility in coding since you can change the type of a variable on the fly. It also reduces verbosity in code, making it easier to work with for beginners and experts alike.
If two variables reference the same object, modifying the object through one variable will affect the other. This is because they both point to the same memory location. This concept is especially important when dealing with mutable data types like lists and dictionaries, where changes to one will reflect in the other.
No, Python requires that a variable must be assigned a value before being used. Attempting to access a variable that hasn’t been assigned will result in a NameError. This is one of Python’s safety features to prevent bugs caused by referencing undefined variables.
Yes, Python allows variables to be assigned values based on conditions using conditional expressions. For instance, the ternary operator x = 10 if y > 5 else 20 will assign 10 to x if y is greater than 5, otherwise 20. This provides a concise way to conditionally set variable values.
Yes, Python variables are case-sensitive, meaning myVariable, MyVariable, and MYVARIABLE are all treated as distinct variables. This is important to remember when naming variables, as accidental case differences could lead to bugs or unexpected behavior in your program.
Python doesn’t have built-in constant variables like other languages. However, you can conventionally indicate constants by using all uppercase letters for variable names (e.g., PI = 3.14). Although Python won’t prevent you from changing these values, it's a widely accepted practice to treat such variables as immutable.
When working with large data (e.g., large lists or dictionaries), Python uses references rather than copying the data for each variable. This saves memory and improves performance since large objects are not duplicated in memory. However, this can also lead to unexpected changes if multiple variables are pointing to the same object.
The global keyword allows you to modify a global variable inside a function. Without it, any assignment to a variable within a function creates a local copy of the variable. The global keyword tells Python to refer to the global variable instead of creating a new local one.
Python variables behave differently because Python is a high-level, dynamically typed language. This contrasts with statically typed languages where variables are explicitly typed and checked at compile time. In Python, variables simply point to objects, and the interpreter handles memory management and type checking at runtime.
You can check if a variable exists using a try-except block or the globals() function. Using globals() allows you to check the variable in the global scope. For example, if 'x' in globals(): checks if the variable x is defined. Alternatively, a try-except block can catch NameError.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.