Variables and Data Types
Prerequisites: Introduction to Python (tokens, identifiers, literals)
1. What Are Variables?
A variable is a name that refers to a value stored in the computer's memory. Think of it as a labelled box that holds a value.
In Python, variables are created the moment you assign a value to them using the assignment operator (=).
# Example 1: Creating variables
name = "Aarav" # string variable
age = 16 # integer variable
marks = 92.5 # float variable
passed = True # boolean variable
Key points about Python variables:
- No need to declare the type (unlike C/Java where you write
int x;), The type is determined automatically based on the assigned value, A variable can change its type during the program (dynamic typing)
2. Assignment Operator (=) and L-value / R-value
x = 10
- L-value (left side):
x, the variable (memory location) that will store the value - R-value (right side):
10, the value or expression to be stored
# Example 2: Assignment in action
a = 5 # a stores 5
b = a + 3 # b stores 8 (a + 3 is evaluated first)
a = a + 1 # a is now 6 (old value 5 + 1)
# INVALID assignments:
# 5 = a # SyntaxError! A literal cannot be an L-value
# a + b = 10 # SyntaxError! An expression cannot be an L-value
3. Dynamic Typing
Python is dynamically typed, you do not need to declare the type of a variable. The type is inferred from the value assigned to it. A variable can even change type during execution.
# Example 3: Dynamic typing
x = 10 # x is int
print(type(x)) # <class 'int'>
x = "Hello" # x is now str (type changed!)
print(type(x)) # <class 'str'>
x = 3.14 # x is now float
print(type(x)) # <class 'float'>
x = True # x is now bool
print(type(x)) # <class 'bool'>
Output:
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>
This is different from C/Java where int x = 10; means x is always an integer.
4. Data Types in Detail
Python has several built-in data types. The most important ones :
4.1 int (Integer)
Whole numbers (positive, negative, or zero) without a decimal point. Python 3 integers have no size limit (can be arbitrarily large).
# Example 4: Integer types
a = 25 # decimal (base 10)
b = -100 # negative integer
c = 0 # zero
# Other number systems
d = 0b1101 # binary (base 2) - value is 13
e = 0o17 # octal (base 8) - value is 15
f = 0xFF # hexadecimal (base 16) - value is 255
g = 0xA5 # hexadecimal - value is 165
print(d) # 13 (Python converts to decimal for display)
print(e) # 15
print(f) # 255
# Very large integers (no overflow in Python!)
big = 10 ** 100 # 1 followed by 100 zeros
print(type(big)) # <class 'int'>
Output:
13
15
255
<class 'int'>
4.2 float (Floating Point)
Numbers with a decimal point, or numbers in scientific notation.
# Example 5: Float types
a = 3.14 # standard decimal
b = -2.5 # negative float
c = 0.0 # zero as float
d = 1.5e2 # scientific notation = 1.5 x 10^2 = 150.0
e = 2.5E-3 # scientific notation = 2.5 x 10^-3 = 0.0025
f = 7.0 # integer value stored as float
print(d) # 150.0
print(e) # 0.0025
print(type(f)) # <class 'float'>
Output:
150.0
0.0025
<class 'float'>
Important: 7 / 2 gives 3.5 (float), even if both operands are integers. Division always returns a float in Python 3.
4.3 complex (Complex Numbers)
Numbers with a real part and an imaginary part. The imaginary part is denoted by j or J.
# Example 6: Complex numbers
z = 3 + 4j
print(z) # (3+4j)
print(z.real) # 3.0 (real part)
print(z.imag) # 4.0 (imaginary part)
print(type(z)) # <class 'complex'>
w = complex(2, 5) # another way to create: 2 + 5j
print(w) # (2+5j)
Output:
(3+4j)
3.0
4.0
<class 'complex'>
(2+5j)
4.4 bool (Boolean)
Has only two values: True and False. Internally, True is 1 and False is 0.
# Example 7: Boolean type
x = True
y = False
print(type(x)) # <class 'bool'>
print(x + x) # 2 (True + True = 1 + 1)
print(x + y) # 1 (True + False = 1 + 0)
print(x * 10) # 10 (True * 10 = 1 * 10)
# Boolean from comparisons
print(5 > 3) # True
print(10 == 20) # False
print(type(5 > 3)) # <class 'bool'>
Output:
<class 'bool'>
2
1
10
True
False
<class 'bool'>
4.5 str (String)
A sequence of characters enclosed in quotes. Strings can use single quotes, double quotes, or triple quotes.
# Example 8: String types
s1 = 'Hello' # single quotes
s2 = "World" # double quotes
s3 = '''This is a
multi-line string''' # triple quotes (preserves newlines)
s4 = "He said, \"Hi!\"" # escape sequence for double quote
s5 = 'It\'s Python' # escape sequence for single quote
s6 = "" # empty string
print(s1)
print(s3)
print(s4)
print(s5)
print(len(s6)) # 0 (empty string has length 0)
Output:
Hello
This is a
multi-line string
He said, "Hi!"
It's Python
0
Common escape sequences:
| Escape Sequence | Meaning |
|---|---|
\n |
Newline (move to next line) |
\t |
Tab (horizontal tab space) |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
# Escape sequences in action
print("Line1\nLine2") # prints on two lines
print("Col1\tCol2") # prints with tab space
print("Path: C:\\Users") # prints: Path: C:\Users
Output:
Line1
Line2
Col1 Col2
Path: C:\Users
4.6 list
An ordered, mutable collection of items enclosed in square brackets.
marks = [85, 92, 78, 95, 88]
mixed = [1, "hello", 3.14, True]
empty = []
print(marks[0]) # 85 (first element, index starts at 0)
print(type(marks)) # <class 'list'>
4.7 tuple
An ordered, immutable collection of items enclosed in parentheses.
colors = ("red", "green", "blue")
print(colors[1]) # green
print(type(colors)) # <class 'tuple'>
# colors[0] = "yellow" # ERROR! Tuples are immutable
4.8 dict (Dictionary)
An unordered collection of key-value pairs enclosed in curly braces.
student = {"name": "Priya", "age": 16, "marks": 95}
print(student["name"]) # Priya
print(type(student)) # <class 'dict'>
4.9 None
A special type representing the absence of a value or a null value. Its type is NoneType.
x = None
print(x) # None
print(type(x)) # <class 'NoneType'>
5. Summary Table of Data Types
| Type | Example | Mutable? | Category |
|---|---|---|---|
int |
10, -5, 0b101 |
Immutable | Numeric |
float |
3.14, 1.5e2 |
Immutable | Numeric |
complex |
3+4j |
Immutable | Numeric |
bool |
True, False |
Immutable | Boolean |
str |
"Hello" |
Immutable | Sequence |
list |
[1, 2, 3] |
Mutable | Sequence |
tuple |
(1, 2, 3) |
Immutable | Sequence |
dict |
{"a": 1} |
Mutable | Mapping |
set |
{1, 2, 3} |
Mutable | Set |
NoneType |
None |
Immutable | Special |
6. Mutable vs Immutable Types (CRITICAL Concept)
This is one of the most important concepts in Python and is frequently tested in exams.
Immutable Types
Once created, their value cannot be changed in memory. If you "change" the value, Python creates a new object in memory.
Immutable types: int, float, str, tuple, bool, complex, NoneType
# Example 9: Immutability of integers
a = 10
print(id(a)) # e.g., 140234866723600 (memory address)
a = 20 # NOT modifying the old object!
print(id(a)) # e.g., 140234866723920 (DIFFERENT address!)
# Python created a NEW integer object 20 and pointed 'a' to it
# The old object 10 still exists (until garbage collected)
# Example 10: Immutability of strings
s = "Hello"
# s[0] = "h" # TypeError: 'str' object does not support item assignment
# You cannot change individual characters of a string
s = "hello" # This creates a NEW string object (does not modify "Hello")
Mutable Types
Their contents can be changed in place without creating a new object. The memory address remains the same.
Mutable types: list, dict, set
# Example 11: Mutability of lists
marks = [85, 92, 78]
print(id(marks)) # e.g., 140234866001280
marks[0] = 90 # modifying the SAME list object
print(marks) # [90, 92, 78]
print(id(marks)) # e.g., 140234866001280 (SAME address!)
marks.append(88) # adding to the SAME list
print(marks) # [90, 92, 78, 88]
print(id(marks)) # SAME address (object modified in place)
Why Does Mutability Matter?
# Immutable (int): separate copies
a = 10
b = a # b gets a copy of the value
b = 20 # changing b does NOT affect a
print(a) # 10 (unchanged)
print(b) # 20
# Mutable (list): shared reference!
x = [1, 2, 3]
y = x # y points to the SAME list object
y.append(4) # modifying through y also affects x!
print(x) # [1, 2, 3, 4] (CHANGED!)
print(y) # [1, 2, 3, 4]
7. The type Function
Returns the data type of a value or variable.
# Example 12: type function
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(type([1, 2])) # <class 'list'>
print(type((1, 2))) # <class 'tuple'>
print(type({"a": 1})) # <class 'dict'>
print(type(3+4j)) # <class 'complex'>
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'NoneType'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'complex'>
8. The id Function
Returns the memory address (identity) of an object. Useful for understanding mutability and object references.
# Example 13: id function
a = 10
b = 10
print(id(a)) # e.g., 140234866723600
print(id(b)) # e.g., 140234866723600 (SAME! Python reuses small integers)
print(a is b) # True (same object in memory)
c = 300
d = 300
print(id(c)) # e.g., 140234866123456
print(id(d)) # may or may not be same (depends on implementation)
# Strings
s1 = "hello"
s2 = "hello"
print(id(s1) == id(s2)) # True (Python caches/interns short strings)
Note: Python caches small integers (typically -5 to 256) and short strings for performance. This is an implementation detail, not something to rely on.
9. Multiple Assignment
Python allows assigning values to multiple variables in a single statement.
# Example 14: Multiple assignment styles
# Assign different values to different variables
a, b, c = 10, 20, 30
print(a, b, c) # 10 20 30
# Assign same value to multiple variables
x = y = z = 0
print(x, y, z) # 0 0 0
# Unpack a list/tuple into variables
name, age, grade = ["Aarav", 16, "XI"]
print(name) # Aarav
print(age) # 16
print(grade) # XI
Output:
10 20 30
0 0 0
Aarav
16
XI
Error case: Number of variables must match number of values.
# a, b = 10, 20, 30 # ValueError: too many values to unpack
# a, b, c = 10, 20 # ValueError: not enough values to unpack
10. Swapping Variables
Python makes swapping two variables extremely easy, no temporary variable needed.
# Example 15: Swapping variables
# Python way (elegant!)
a = 5
b = 10
a, b = b, a
print(a, b) # 10 5
# Traditional way (using temp variable -- other languages)
x = 5
y = 10
temp = x
x = y
y = temp
print(x, y) # 10 5
Output:
10 5
10 5
The Python way a, b = b, a works because the right side is evaluated completely before the assignment happens.
Common Mistakes
- Assuming
typereturns just a type name: It returns<class 'int'>, not justint. In comparisons, usetype(x) == int(nottype(x) == "int") - Confusing
=and==:=is assignment,==is comparison.x = 5assigns;x == 5checks equality - Thinking strings are mutable:
s = "Hello"; s[0] = "h"causesTypeError. Strings cannot be changed in place - Misunderstanding mutable aliasing: When two variables point to the same list, changing one changes both (see Example 11)
- Forgetting
inputreturns a string:age = input("Age: ")gives a string, not an integer. Must useint(input("Age: ")) - Confusing
0b,0o,0xprefixes:0bis binary,0ois octal,0xis hexadecimal - Not knowing that
True= 1 andFalse= 0:True + Truegives2, not an error - Mismatched variable count in multiple assignment:
a, b = 1, 2, 3givesValueError - Using
idto compare values:idcompares memory addresses, not values. Use==to compare values - Thinking
Noneis the same as0or"":Noneis a distinct type (NoneType) and is not equal to0,"", orFalse
$1$2 Quick Tips
- "What is dynamic typing?" (2 marks): Explain that Python determines variable type at runtime, no explicit declaration needed, and type can change
- "Differentiate mutable and immutable" (2-3 marks): Give definition + 2-3 examples of each. Use
idto demonstrate typeoutput questions (1-2 marks): Givenx = ..., what doestype(x)return?- "What is the output?" with multiple assignment:
a, b = 10, 20; a, b = b, a; print(a, b) - Integer base conversions (1-2 marks): What is
0b1010? What is0o17? - True/False as numbers (1 mark):
True + True + False= ? - String escape sequences (1-2 marks): What is the output of
print("Hello\nWorld")? - None type questions (1 mark): What is the type of
None? - List vs Tuple (2 marks): Key difference is mutability, lists can be changed, tuples cannot
- id based questions: Given two variables, will they have the same id? (Depends on value and type)
Prefer watching over reading?
Subscribe for free.