Python Data Types
Every value in Python has a type, and the type decides what you can do with it: you can add two numbers, make a string upper case, or append to a list. This lesson is a tour of the built-in types you will use every day.
- The built-in data types at a glance
- Check a value’s type with type() and isinstance()
- Mutable vs immutable types
- Choose the right collection for the job
Built-in data types at a glance
| Category | Type | Example | Notes |
|---|---|---|---|
| Text | str | "hello" | Immutable sequence of characters |
| Numbers | int | 42, -7 | Whole numbers of any size |
float | 3.14, 1e-3 | Decimal numbers | |
complex | 2 + 3j | Used in maths and engineering | |
| Boolean | bool | True, False | Result of comparisons |
| Nothing | NoneType | None | “No value yet” |
| Sequences | list | [1, 2, 3] | Ordered, changeable |
tuple | (1, 2, 3) | Ordered, unchangeable | |
range | range(5) | Sequence of numbers, created on demand | |
| Mapping | dict | {"id": 7} | Key-value pairs |
| Sets | set | {1, 2, 3} | Unique items, no order |
| Binary | bytes | b"abc" | Raw bytes from files and networks |
Check the type of a value
type() returns the exact type of a value:
values = [42, 3.14, 2 + 3j, "py", True, None, [1], (1,), {1}, {"a": 1}, range(3), b"x"]for v in values: print(repr(v).ljust(10), type(v).__name__)42 int
3.14 float
(2+3j) complex
'py' str
True bool
None NoneType
[1] list
(1,) tuple
{1} set
{'a': 1} dict
range(0, 3) range
b'x' bytesUse isinstance() in real code. It also accepts a tuple of types and understands subclasses:
price = 99.5print(isinstance(price, float))print(isinstance(price, (int, float)))print(isinstance(True, int)) # bool is a subclass of intTrue True True
Numbers
big = 2 ** 100 # ints never overflowprint(big)print(7 / 2, 7 // 2) # / always gives a float, // rounds downprint(0.1 + 0.2) # floats are approximate1267650600228229401496703205376 3.5 3 0.30000000000000004
0.1 + 0.2 is not exactly 0.3 because floats are stored in binary. Use round() for display, or the decimal module for money. The Numbers & Math lesson goes deeper.
Strings
A string is text in single, double or triple quotes. Strings support indexing, slicing and many methods.
course = "Python Tutorial"print(course.upper())print(course[0], course[-1])print(len(course))print("Tut" in course)PYTHON TUTORIAL P l 15 True
Booleans and None
True and False come from comparisons and are used by if and while. None means “no value”.
is_logged_in = 5 > 3print(is_logged_in, type(is_logged_in)) result = Noneprint(result is None)True <class 'bool'> True
Every value is either “truthy” or “falsy”. Empty values and zero are falsy:
for v in [0, 1, "", "a", [], [0], None]: print(repr(v).ljust(5), bool(v))0 False 1 True '' False 'a' True [] False [0] True None False
Collections: list, tuple, set, dict
skills = ["python", "sql", "python"] # list: ordered, duplicates allowedpoint = (12.5, 77.3) # tuple: fixed recordunique_skills = set(skills) # set: duplicates removeduser = {"name": "Asha", "role": "tester"} # dict: look up by key print(skills)print(point[0])print(len(unique_skills))print(user["role"])['python', 'sql', 'python'] 12.5 2 tester
| Need | Use |
|---|---|
| An ordered list of items you will change | list |
| A fixed group of values, such as coordinates | tuple |
| Unique items, or fast “is it in here?” checks | set |
| Look up a value by a key | dict |
Mutable vs immutable
A mutable object can change after it is created; an immutable one cannot.
- Immutable:
int,float,bool,str,tuple,frozenset,bytes. - Mutable:
list,dict,set,bytearray.
name = "python"name.upper() # returns a NEW stringprint(name) # the original is unchanged name[0] = "P" # strings cannot be changed in placepython
Traceback (most recent call last):
File "main.py", line 5, in <module>
name[0] = "P" # strings cannot be changed in place
~~~~^^^
TypeError: 'str' object does not support item assignmentBecause lists and dicts are mutable, passing one to a function lets that function change your data. Strings and numbers are safe from that.
Check your understanding
Predict the output
print(type(7 / 7).__name__, type(7 // 7).__name__, type("7").__name__)float int str
/ always returns a float even when the division is exact, // keeps an int for two ints, and anything in quotes is a str.
Quick quiz
1. What is the type of (5,)?
The trailing comma makes it a one-item tuple. (5) without the comma is just the int 5.
2. Which type removes duplicates automatically?
A set keeps only unique items.
3. Which of these is immutable?
Strings cannot be changed in place; methods like upper() return a new string.
4. What does bool([]) return?
Empty collections are falsy.
Exercise: describe each value
Loop over the list and print each value with its type name and whether it is truthy.
[0, 2.5, "", "hi", None, [3]]
0 int False 2.5 float True '' str False 'hi' str True None NoneType False [3] list True
Hint 1
type(v).__name__ gives the type name as a string.
for value in [0, 2.5, "", "hi", None, [3]]: print(f"{value!r:6} {type(value).__name__:9} {bool(value)}")0 int False 2.5 float True '' str False 'hi' str True None NoneType False [3] list True
!r prints the value as Python code (strings keep their quotes), and :6 / :9 pad each column to a fixed width so the output lines up.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python data types FAQ
How many data types are there in Python?
Python has about a dozen commonly used built-in types: int, float, complex, bool, str, list, tuple, range, dict, set, frozenset, bytes and NoneType. You can also create your own with classes.
How do I check the data type of a variable?
Use type(x) to see the type, or isinstance(x, int) to test it.
What is the difference between mutable and immutable types?
Mutable objects such as lists and dicts can be changed in place. Immutable objects such as strings, numbers and tuples cannot; operations on them return new objects.
Is a string a sequence in Python?
Yes. A string is an immutable sequence of characters, so it supports indexing, slicing, len() and in.