In Python, “data type” means the kind of value you are working with: an integer, a piece of text, a list of items, and so on. Understanding data types is one of the fastest ways to reduce confusing bugs and error messages. In this guide we look at the most common built‑in types, how to use them in real code, and how they relate to other topics like operators and lists vs tuples.
1. Why data types matter
Every operation in Python depends on the data type. Adding two integers makes sense, but adding a string and an integer does not and gives you a TypeError. If you know the type, you know which operations are safe and which are not.
price = 19.99 # float
quantity = 3 # int
product = "Notebook" # str
total = price * quantity # OK
label = product + " x " + str(quantity) # OK (after conversion)
# This would raise a TypeError:
# label = product + " x " + quantity
When you see an error message that mentions types, check this page and the detailed error guides in the Errors & Exceptions section.
2. Numeric types
Python has three main numeric types: int, float, and complex. Most beginners only need int and float.
2.1 int (integer)
Whole numbers (positive, negative, or zero):
age = 25
temperature_c = -3
items_in_cart = 0
print(type(age)) # <class 'int'>
print(age + 5) # 30
print(age * 2) # 50
2.2 float (floating‑point)
Numbers with a decimal point. Use them for measurements, prices, and ratios:
price = 19.99
pi = 3.14159
progress = 0.75 # 75%
print(type(price)) # <class 'float'>
print(price * 2) # 39.98
Because of how computers store floats, you may see rounding issues like 0.1 + 0.2 != 0.3. For money you may prefer decimal.Decimal from the standard library.
2.3 complex
Complex numbers have a real and imaginary part. They are mainly used in scientific and engineering code:
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
3. Text: strings (str)
Text is stored as str. Strings can be single‑quoted, double‑quoted, or triple‑quoted for multi‑line text:
name = "Alice"
greeting = 'Hello'
message = """This is
a multi-line string."""
print(len(name)) # 5
print(name.upper()) # ALICE
print("Hello " + name) # Hello Alice
Strings are immutable: every change creates a new string instead of modifying the old one. If you try to call list methods on a string, you will get errors like AttributeError: 'str' object has no attribute 'append'.
4. Boolean values (bool)
The bool type has only two values: True and False. They are used for conditions, comparisons, and if statements.
is_student = True
is_graduated = False
print(5 > 3) # True
print(5 == 3) # False
Any value can be converted to a boolean with bool(x). Empty containers (like [], {}, "") are False, non‑empty ones are True. This is useful in conditions:
items = []
if not items:
print("Cart is empty")
5. Sequences: list, tuple, range
Sequence types model ordered collections of items.
5.1 list
Lists are ordered and mutable (you can change them in place). They are the workhorse of everyday Python code.
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits[0]) # apple
print(fruits[-1]) # grape
print(len(fruits)) # 4
Lists are often used with for loops and comprehensions. For more patterns see Working with lists and List comprehensions.
5.2 tuple
Tuples are ordered but immutable. Use them for fixed‑size records that should not change, such as coordinates or function return values:
point = (10, 20)
user = ("alice", "admin")
print(point[0]) # 10
# point[0] = 5 # TypeError: 'tuple' object does not support item assignment
Choosing between list and tuple is a common question; see Lists vs Tuples for a deeper comparison.
5.3 range
range represents a sequence of numbers, usually used in loops:
for i in range(3):
print(i) # 0, 1, 2
evens = range(0, 10, 2)
print(list(evens)) # [0, 2, 4, 6, 8]
6. Mappings: dictionaries (dict)
Dictionaries map keys to values, like a simple in‑memory database. They are unordered until Python 3.6/3.7, but in modern Python they preserve insertion order.
person = {
"name": "Alice",
"age": 30,
"city": "New York",
}
print(person["name"]) # Alice
person["email"] = "[email protected]"
print(person.keys())
If you access a missing key, you will get a KeyError. To avoid this, use dict.get() with a default value:
country = person.get("country", "Unknown")
Dictionaries are the natural format for JSON objects from APIs. See How to read and write JSON for practical examples.
7. Sets: unique unordered collections
Sets store unique items and are optimized for membership tests like “is this element present?”. Order is not guaranteed.
colors = {"red", "green", "blue"}
colors.add("green") # no effect, already present
colors.add("yellow")
print(colors)
You can use set operations to compare groups of items:
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # intersection: {3}
print(a | b) # union: {1, 2, 3, 4, 5}
frozenset is an immutable version of a set, useful as dictionary keys or elements of other sets.
8. The special value None
None represents “no value”. It has its own type, NoneType, and is often used as a default return value or placeholder.
result = None
print(result is None) # True
A very common beginner bug is to treat None like a list or string, which leads to errors like TypeError: object of type 'NoneType' has no len() or TypeError: 'NoneType' object is not subscriptable. Whenever you see NoneType in an error, check where None came from.
9. Checking and converting types
You can inspect the type of a value with type() and check if it matches a specific type with isinstance():
x = 42
y = "hello"
z = [1, 2, 3]
print(type(x)) # <class 'int'>
print(isinstance(y, str)) # True
print(isinstance(z, list)) # True
Conversions let you change between compatible types:
age_str = "25"
age_int = int(age_str) # 25
numbers = [1, 2, 2, 3]
unique = set(numbers) # {1, 2, 3}
coords_list = [1, 2, 3]
coords_tuple = tuple(coords_list) # (1, 2, 3)
When converting user input, always be prepared for errors like ValueError: invalid literal for int() and handle them with try/except.
10. Mutable vs immutable in practice
Some types are mutable (can be changed), others are immutable. This affects how variables behave when you pass them to functions or assign them to new names.
# Mutable example
items = [1, 2, 3]
alias = items
alias.append(4)
print(items) # [1, 2, 3, 4]
# Immutable example
text = "hi"
alias = text
alias = alias + "!"
print(text) # "hi" (unchanged)
Understanding mutability helps avoid surprises with lists and dictionaries being modified in functions. See also Mutable vs immutable objects if you add a dedicated concept article.
11. Summary and next steps
Data types are the foundation of every Python program. You now know:
- How integers, floats, strings, booleans, lists, tuples, ranges, dictionaries, and sets behave.
- What
Nonerepresents and whyNoneTypeappears in errors. - How to inspect and convert types safely.
From here, continue with:
- Operators – how to combine and compare values.
- Lists and dictionaries – the two most used container types.
- Read and write JSON – a practical example where dictionaries and lists map directly to real‑world data.
Numeric types
int (Integer)
Whole numbers (positive, negative, or zero):
age = 25
temperature = -10
count = 0
print(type(age)) #
print(age + 5) # 30
float (Floating-point number)
Numbers with decimal points:
price = 19.99
pi = 3.14159
temperature = 98.6
print(type(price)) #
print(price * 2) # 39.98
complex (Complex number)
Numbers with real and imaginary parts (less common):
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
Text type
str (String)
Text data, enclosed in quotes:
name = "Alice"
greeting = 'Hello'
message = """Multi-line
string"""
print(type(name)) #
print(len(name)) # 5
print(name.upper()) # ALICE
print("Hello " + name) # Hello Alice
Boolean type
bool (Boolean)
True or False values:
is_student = True
is_graduated = False
print(type(is_student)) #
print(5 > 3) # True
print(5 == 3) # False
Sequence types
list (List)
Ordered, changeable collection of items:
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
print(type(fruits)) #
print(fruits[0]) # apple
fruits.append("grape") # Add item
print(fruits) # ['apple', 'banana', 'orange', 'grape']
tuple (Tuple)
Ordered, unchangeable collection of items:
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # Note the comma for single item
print(type(coordinates)) #
print(coordinates[0]) # 10
# coordinates[0] = 5 # Error! Tuples are immutable
range (Range)
Sequence of numbers (used in loops):
numbers = range(5) # 0 to 4
evens = range(0, 10, 2) # 0, 2, 4, 6, 8
print(type(numbers)) #
print(list(numbers)) # [0, 1, 2, 3, 4]
print(list(evens)) # [0, 2, 4, 6, 8]
Mapping type
dict (Dictionary)
Key-value pairs, unordered, changeable:
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(type(person)) #
print(person["name"]) # Alice
person["email"] = "[email protected]" # Add new key-value
print(person.keys()) # dict_keys(['name', 'age', 'city', 'email'])
Set types
set (Set)
Unordered collection of unique items:
unique_numbers = {1, 2, 3, 4, 5}
colors = {"red", "green", "blue"}
print(type(unique_numbers)) #
unique_numbers.add(6) # Add item
unique_numbers.add(3) # Won't add duplicate
print(unique_numbers) # {1, 2, 3, 4, 5, 6}
frozenset (Frozen Set)
Immutable version of a set:
frozen = frozenset([1, 2, 3])
print(type(frozen)) #
# frozen.add(4) # Error! Frozen sets are immutable
None type
NoneType
Represents the absence of a value:
value = None
print(type(value)) #
print(value is None) # True
Checking data types
Use type() to check what type a variable is:
x = 42
y = "hello"
z = [1, 2, 3]
print(type(x)) #
print(type(y)) #
print(type(z)) #
# Check if specific type:
print(isinstance(x, int)) # True
print(isinstance(y, str)) # True
Type conversion
Convert between different types:
# String to number
age_str = "25"
age_int = int(age_str) # 25
price_str = "19.99"
price_float = float(price_str) # 19.99
# Number to string
age = 25
age_str = str(age) # "25"
# List to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # (1, 2, 3)
# Tuple to list
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # [1, 2, 3]
# List to set (removes duplicates)
numbers = [1, 2, 2, 3, 3, 4]
unique = set(numbers) # {1, 2, 3, 4}
Mutable vs immutable
Mutable (can be changed)
list— can add, remove, modify itemsdict— can add, remove, modify key-value pairsset— can add, remove items
Immutable (cannot be changed)
int,float,str— create new value when modifiedtuple— cannot modify after creationfrozenset— cannot modify after creation
# Mutable example
my_list = [1, 2, 3]
my_list[0] = 10 # OK
print(my_list) # [10, 2, 3]
# Immutable example
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error! Cannot modify tuple
Summary table
| Type | Mutable? | Ordered? | Example |
|---|---|---|---|
int |
No | N/A | 42 |
float |
No | N/A | 3.14 |
str |
No | Yes | "hello" |
bool |
No | N/A | True |
list |
Yes | Yes | [1, 2, 3] |
tuple |
No | Yes | (1, 2, 3) |
dict |
Yes | Yes (Python 3.7+) | {"key": "value"} |
set |
Yes | No | {1, 2, 3} |
Common mistakes
- Confusing
==andis: Use==to compare values,isto check identity (especially withNone) - Modifying immutable types: Trying to change a tuple or string directly will cause an error
- Type errors: Make sure to convert types when needed (e.g.,
int("5")instead of treating string as number) - List vs tuple: Use lists when you need to modify, tuples when you need fixed data
Best practices
- Use appropriate types: Choose the right type for your data (list for ordered items, dict for key-value pairs, set for unique items)
- Check types when needed: Use
isinstance()to verify types before operations - Convert safely: Always handle errors when converting types (use try-except if needed)
- Prefer tuples for constants: Use tuples for data that shouldn't change
Next steps
Now that you understand data types, learn about operators to work with them, or explore specific types in detail: lists, dictionaries, tuples, and sets.