Python ProgrammingBeginner8 min read read

Python Variables and Data Types: A Comprehensive Guide

Master dynamic typing, primitive types, sequence containers, and mutability in modern Python.

Coding Hub Technical Editorial Team(Software Engineering & Education)
•
Updated 2026-03-12

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.

What You Will Learn
Understand variable naming conventions (PEP 8 snake_case)
Distinguish between primitive types (int, float, bool, str) and collection types
Master the fundamental difference between mutable and immutable data structures
Perform safe explicit type conversions using int(), float(), and str()

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.

python
# 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 str
Key note: Rebinding `item` simply redirects the reference pointer to a new string object; the initial integer is garbage collected if no other references exist.

2. 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.

python
# 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.8
Key note: Dictionaries provide fast hash-based lookups, making them the standard data container for API responses and table records.

4. 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()`).

Common Mistake to Avoid
  • 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.

python
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%
Key note: Formatting with `:.1f` inside an f-string rounds the displayed floating-point number to one decimal place.

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.
Frequently Asked Questions

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.