Python Data Types
Python's core data types: numbers, strings, booleans, lists, tuples, dictionaries, and sets.
What you'll learn
- The core numeric types: int and float
- Strings and their most useful operations
- Booleans and the truthy/falsy values
- Collections: list, tuple, dict, and set
- Mutable vs immutable types and why it matters
Concept
Numeric Types
Python has two main numeric types:
int— integers of arbitrary precision (no overflow!)float— floating-point numbers (IEEE 754 double)
count = 42 # int
price = 19.99 # float
big = 10 ** 100 # int — Python handles arbitrarily large integers
Strings
Strings are text, enclosed in single, double, or triple quotes:
name = "Ada"
greeting = 'Hello'
multi = """This is a
multi-line string"""
# F-strings (Python 3.6+) — the best way to format
message = f"Hello, {name}!"
Strings have useful methods: .upper(), .lower(), .strip(), .split(), .replace(), .startswith().
Booleans
is_active = True
is_deleted = False
Falsy values: False, 0, 0.0, "", [], {}, None. Everything else is truthy.
Collections
list — ordered, mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] = "apricot" # mutable
tuple — ordered, immutable
point = (10, 20)
# point[0] = 5 # TypeError — tuples cannot be changed
dict — key-value pairs
user = {"name": "Ada", "age": 25}
user["email"] = "[email protected]" # add a key
print(user["name"])
set — unordered, unique elements
tags = {"python", "code", "learn"}
tags.add("fun")
tags.add("python") # no effect — already exists
Mutable vs Immutable
This is a crucial distinction:
- Immutable —
int,float,str,tuple,bool. Once created, their value cannot change. "Changing" a string creates a new string. - Mutable —
list,dict,set. You can modify them in place.
# Strings are immutable
s = "hello"
s += " world" # creates a NEW string, s now points to it
# Lists are mutable
nums = [1, 2, 3]
nums.append(4) # modifies the SAME list
Checking Types
type(x) # returns the type
isinstance(x, int) # True if x is an int (or subclass)
Use isinstance() for type checks — it handles inheritance, while type() does not.
Example
# Numbers
count = 42
price = 19.99
big = 10 ** 50 # Python handles big integers natively
print(f"Count: {count}, Price: {price}, Big: {big}")
# Strings and f-strings
name = "Ada"
print(f"Hello, {name}!")
print(name.upper()) # ADA
print(name.replace("A", "E")) # Eda
# Lists — ordered and mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits)
print(fruits[0]) # apple
print(fruits[-1]) # date (negative indexing)
# Dictionaries — key-value pairs
user = {"name": "Ada", "age": 25, "role": "admin"}
print(user["name"])
for key, value in user.items():
print(f" {key}: {value}")
# Tuples — immutable
point = (10, 20)
x, y = point # unpacking
print(f"Point: ({x}, {y})")
# Sets — unique elements
tags = {"python", "code", "python"} # duplicates removed
print(tags) # {'python', 'code'}
# Type checking
print(type(count)) # <class 'int'>
print(isinstance(name, str)) # True
Demonstrates numbers, f-strings, list operations, dict iteration, tuple unpacking, set deduplication, and type checking. These are the types you will use every day in Python.
Try it
- JSON Formatter
Python dicts and lists map directly to JSON — format and inspect them.
- CSV to JSON
Convert CSV data into Python-style dicts — a common data task.
Common mistakes
The mistake
Using a list as a default argument in a function
The fix
Default arguments are evaluated once, not on each call. def f(x=[]): x.append(1) will accumulate across calls. Use def f(x=None): x = x or [] instead.
The mistake
Expecting a tuple to be mutable like a list
The fix
Tuples are immutable — you cannot append, remove, or reassign elements. If you need to modify a sequence, use a list. Use tuples for fixed collections like coordinates.
Related Resources
Related Snippets
- Sort Dictionary by Value
A practical example of working with dictionaries.
Related Cheatsheets
- Python Cheatsheet
All data types with methods and operations.
Practice Python Data Types
1 exercise
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.