By the end of this lesson, you will understand how Python variables store data and be able to identify and use the core built-in data types.
What it is
In Python, a variable is a name that refers to an object in memory. Unlike languages like C or Java, Python does not require you to declare a variable's type explicitly. Instead, Python uses dynamic typing: the type is determined at runtime based on the value assigned. Every piece of data in Python is an object, and variables are simply labels pointing to these objects.
The core immutable data types include int (integers), float (decimal numbers), str (text strings), and bool (True/False). The primary mutable collection types are list (ordered, changeable), tuple (ordered, unchangeable), set (unordered, unique items), and dict (key-value pairs).
Why it matters
- Flexibility: You can write code faster without worrying about type declarations during development.
- Data Structure Choice: Understanding types allows you to choose the right container for your data (e.g., using a
setfor fast lookups vs. alistfor ordered storage). - Error Prevention: Knowing which types are mutable helps prevent bugs where unintended changes affect other parts of your program.
- Interoperability: Correctly handling types ensures smooth interaction with libraries and APIs that expect specific data formats.
Syntax or steps
To create a variable, use the assignment operator =. The syntax is variable_name = value. Variable names must start with a letter or underscore, contain only alphanumeric characters and underscores, and cannot be reserved keywords.
- Choose a descriptive name for your variable.
- Assign a value using
=. - Use the
type()function to verify the data type if needed.
Example
# Integer and Float
age = 30
price = 19.99
# String
name = "Alice"
# Boolean
is_active = True
# List (mutable, ordered)
fruits = ["apple", "banana", "cherry"]
# Tuple (immutable, ordered)
coordinates = (10.5, 20.3)
# Set (unique, unordered)
unique_ids = {101, 102, 103}
# Dictionary (key-value pairs)
person = {"name": "Bob", "age": 25}
print(type(age)) # <class 'int'>
print(fruits[0]) # apple
person["age"] = 26 # Updating dictionary value
print(person)
This example demonstrates creating variables of each core type. Note that lists and dictionaries allow modification after creation, while tuples do not. The print(type()) call confirms the inferred type.
Common mistakes
- Assuming Static Typing: Reassigning a variable to a different type (e.g.,
x = 5thenx = "hello") is valid but can lead to confusing errors later if not handled carefully. - Mutating Default Arguments: Using a mutable list as a default argument in functions can cause unexpected state retention between calls.
- Confusing Lists and Tuples: Trying to modify a tuple (e.g.,
t[0] = 1) raises aTypeError. Use lists if you need to change elements. - Unhashable Types in Sets/Dict Keys: You cannot use lists or dictionaries as keys in a dictionary or elements in a set because they are mutable and unhashable.
When to use it
Choosing the right data type depends on whether your data needs to be ordered, unique, or modifiable.
| Type | Ordered? | Mutable? | Best For |
|---|---|---|---|
list | Yes | Yes | Collections that change size or content. |
tuple | Yes | No | Fixed records, e.g., coordinates or RGB values. |
set | No | Yes | Removing duplicates or membership testing. |
dict | Yes* | Yes | Mapping keys to values for quick lookup. |
*Note: Dictionaries maintain insertion order in Python 3.7+.
Practice
Guided Exercise: Create a dictionary representing a book with keys "title", "author", and "pages". Print the author's name.
Challenge: Convert the list [1, 2, 2, 3, 4, 4] into a set to remove duplicates, then convert it back to a sorted list.
Hint: Use set() and sorted() functions.
Quick check
Question: What happens if you try to assign a new value to an index in a tuple?
Answer: Python raises a TypeError because tuples are immutable.
Summary
Python variables are dynamic references to objects, allowing flexible coding styles. Mastering the distinction between mutable types like lists and dicts versus immutable types like tuples and strings is crucial for writing robust and efficient Python programs.