Python Variables and Data Types: A Comprehensive Guide
Master dynamic typing, primitive types, sequence containers, and mutability in modern Python.
Overview & Context
In many compiled programming languages, a variable is a named memory location with a fixed, strictly enforced type. In Python, variables work differently: they are lightweight labels or references bound to underlying objects in heap memory. Because Python is dynamically typed, you do not declare a variable's type upfront; the interpreter infers the type automatically at runtime based on the value assigned.
1. Variable Declaration & Memory References
Assignment operator and PEP 8 naming standards
To create a variable in Python, assign an object to a name using the `=` operator.
According to Python's official PEP 8 style guide, variable and function names must use lowercase letters separated by underscores (`snake_case`). Variable names cannot start with a digit, cannot contain punctuation, and should never shadow Python built-in keywords.
# Variable assignment and dynamic reassignment
semester_gpa = 8.75 # float
student_count = 120 # integer
is_active_term = True # boolean
course_code = "CS-201" # string
# In Python, variables can be rebound to different types:
item = 42 # item refers to an int
item = "Forty-Two" # item now refers to a str2. Primitive Data Types
Integers, Floats, Booleans, and Strings
Integers (`int`) in Python 3 have arbitrary precision, meaning they can grow to accommodate arbitrarily large numbers limited only by available system RAM.
Floats (`float`) implement standard IEEE 754 double-precision numbers. Booleans (`bool`) have two states: `True` and `False`.
Strings (`str`) are immutable sequences of Unicode characters, supporting multi-language characters out of the box.
3. Collection Types: Lists, Tuples, Dictionaries & Sets
Choosing the correct container for your data
Lists (`list`) are ordered, mutable sequences enclosed in square brackets `[]`.
Tuples (`tuple`) are ordered, immutable sequences enclosed in parentheses `()`.
Dictionaries (`dict`) are key-value mappings enclosed in curly braces `{}` with unique keys and O(1) average lookup times.
Sets (`set`) are unordered collections of unique elements, useful for deduplication and membership checks.
# Collections in action
exam_scores = [88, 92, 79, 95] # Mutable list
fixed_dimensions = (1920, 1080) # Immutable tuple
unique_student_ids = {101, 102, 103, 101} # Set removes duplicate 101
# Dictionary mapping student IDs to grade averages
grade_book = {
"S101": 8.8,
"S102": 7.4,
"S103": 9.1
}
print("Unique IDs count:", len(unique_student_ids)) # Output: 3
print("Student S101 GPA:", grade_book["S101"]) # Output: 8.84. Mutability vs Immutability
Understanding mutability is crucial in Python. Immutable objects (strings, integers, floats, tuples) cannot be modified in place after creation; modifying them produces a new object.
Mutable objects (lists, dictionaries, sets) can be modified in place without changing their identity memory address (`id()`).
- Assuming `b = a` copies a list. In Python, assigning a list to a new variable copies the reference, not the data. Modifying `b` will modify `a`! Use `b = a.copy()` or `list(a)` to create an independent shallow copy.
5. Explicit Type Casting & Best Practices
User input from terminals or web forms always arrives as strings. Use `int()`, `float()`, or `str()` to explicitly convert between data types.
raw_input_marks = "95"
total_possible_marks = 100
# Explicitly cast to float before math operations
percentage = (float(raw_input_marks) / total_possible_marks) * 100
print(f"Calculated Percentage: {percentage:.1f}%") # Output: 95.0%Summary & Key Takeaways
- 1Variables in Python are reference labels attached to objects in memory.
- 2Primitive types: int (arbitrary precision), float (double precision), bool, str.
- 3Lists and dictionaries are mutable; tuples, strings, and numbers are immutable.
- 4Always use PEP 8 snake_case for variable names.
Why does Python not require variable type declarations?
Python is dynamically typed: the interpreter checks and enforces types at runtime when operations occur, rather than checking during an ahead-of-time compile step. Python 3.6+ supports optional type hints (e.g. `age: int = 20`) for static analysis with tools like Mypy.
When should I use a tuple instead of a list?
Use tuples when you have a fixed collection of heterogeneous items that should never change (like coordinates or database records). Tuples use slightly less memory than lists and prevent accidental mutation bugs.
Recommended Practical Tools
Next Recommended Reads
Discover Python's core design philosophy, interpreted execution model, dynamic typing, and why readability makes it the optimal first language.
A practical guide to writing clean, modular Python functions. Master argument passing, *args and **kwargs, return tuples, and docstrings.
Learn essential data hygiene practices. Master how to handle missing data with Pandas, detect statistical outliers with IQR, and standardize categorical values.