W3docs

Python Data Types: A Comprehensive Guide

Learn all Python built-in data types — int, float, str, bool, list, tuple, set, dict, and NoneType — with clear examples and when to use each.

Every value in Python has a data type that tells the interpreter what kind of data it is and what operations are allowed on it. Because Python is dynamically typed, you never declare a type explicitly — the interpreter infers it at runtime. Understanding the built-in types is therefore essential: picking the wrong type leads to bugs, unnecessary copying, or poor performance.

This chapter covers every built-in data type:

CategoryTypes
Numericint, float, complex
Textstr
Booleanbool
Sequencelist, tuple
Setset
Mappingdict
NoneNoneType

Use the built-in type() function at any point to inspect what type a value has:

print(type(42))       # <class 'int'>
print(type(3.14))     # <class 'float'>
print(type("hello"))  # <class 'str'>
print(type(True))     # <class 'bool'>
print(type([1, 2]))   # <class 'list'>
print(type((1, 2)))   # <class 'tuple'>
print(type({1, 2}))   # <class 'set'>
print(type({"a": 1})) # <class 'dict'>
print(type(None))     # <class 'NoneType'>

Numeric Types

Python has three numeric types: int, float, and complex. All three support standard arithmetic operators (+, -, *, /, //, %, **).

int

An int stores a whole number of unlimited size — Python integers are not limited to 32 or 64 bits.

Key operators

OperatorMeaningExampleResult
+Addition1 + 23
-Subtraction3 - 12
*Multiplication2 * 36
/True division6 / 23.0
//Floor division7 // 23
%Remainder7 % 21
**Exponentiation2 ** 101024

Notice that / always returns a float even when the result is a whole number. Use // when you need an integer quotient.

Python Integer data type

# Integer addition
print(1 + 2)    # 3

# Integer subtraction
print(3 - 1)    # 2

# Integer multiplication
print(2 * 3)    # 6

# True division always returns float
print(6 / 2)    # 3.0

# Floor division returns int
print(7 // 2)   # 3

# Exponentiation
print(2 ** 10)  # 1024

float

A float stores a decimal number using IEEE 754 double-precision. Use floats whenever you need fractional values.

Gotcha — floating-point representation: 0.1 + 0.2 is not exactly 0.3 in binary floating-point. Use round() or the decimal module when exact decimal arithmetic matters (e.g., currency).

python— editable, runs on the server

complex

A complex number has a real part and an imaginary part, written as a + bj in Python (using j, not i). Complex numbers are mainly used in scientific computing, signal processing, and engineering calculations.

python— editable, runs on the server

str (Strings)

A str is an immutable sequence of Unicode characters. Strings can be enclosed in single quotes, double quotes, or triple quotes (for multi-line strings).

single = 'Hello'
double = "World"
multi  = """This spans
multiple lines."""

Common string operations

python— editable, runs on the server

Useful string methods

s = "  Hello World  "
print(s.strip())          # "Hello World"  — remove whitespace
print(s.strip().lower())  # "hello world"
print(s.strip().upper())  # "HELLO WORLD"
print("Hello World".split())   # ['Hello', 'World']
print(",".join(["a", "b", "c"]))  # a,b,c
print("Hello World".replace("World", "Python"))  # Hello Python
print(len("Hello"))       # 5

f-strings (formatted string literals)

f-strings (introduced in Python 3.6) are the preferred way to embed values inside strings:

name = "Alice"
age  = 30
print(f"{name} is {age} years old.")   # Alice is 30 years old.
print(f"Next year she will be {age + 1}.")  # Next year she will be 31.

Because strings are immutable, every operation that "changes" a string actually creates a new one. For more on string methods, see the Python Strings chapter.

bool (Boolean)

A bool has exactly two values: True and False. Booleans are a subclass of int in Python — True equals 1 and False equals 0.

print(type(True))   # <class 'bool'>
print(True + 1)     # 2  (True is treated as 1)
print(False + 10)   # 10 (False is treated as 0)

Truthy and falsy values

Every Python object can be evaluated in a boolean context. The following values are falsy (evaluate to False); everything else is truthy:

  • False, None
  • Numeric zero: 0, 0.0, 0j
  • Empty sequences: "", [], (), set()
  • Empty mapping: {}
print(bool(0))      # False
print(bool(""))     # False
print(bool([]))     # False
print(bool(None))   # False

print(bool(42))     # True
print(bool("hi"))   # True
print(bool([0]))    # True  — list with one item is truthy

For a full treatment see the Python Booleans chapter.

list

A list is an ordered, mutable sequence. It can hold items of any type, including a mix of types, and allows duplicates.

# Creating a list
fruits = ["apple", "banana", "cherry"]

# Modifying an item
fruits[1] = "orange"
print(fruits)  # ['apple', 'orange', 'cherry']

# Adding items
fruits.append("mango")
print(fruits)  # ['apple', 'orange', 'cherry', 'mango']

# Removing an item
fruits.remove("orange")
print(fruits)  # ['apple', 'cherry', 'mango']

# Length
print(len(fruits))  # 3

When to use a list: when you need an ordered collection that will change — add items, remove items, or update values in place. For deep coverage see the Python Lists chapter.

tuple

A tuple is an ordered, immutable sequence. Once created, its elements cannot be changed.

# Creating a tuple
coords = (10, 20)
print(coords[0])    # 10
print(len(coords))  # 2

# Tuple unpacking
x, y = coords
print(x, y)  # 10 20

# Single-element tuple needs a trailing comma
single = (42,)
print(type(single))  # <class 'tuple'>

When to use a tuple instead of a list:

  • The data should not change (e.g., GPS coordinates, RGB colour values, database rows).
  • You want to use the value as a dictionary key (lists cannot be dict keys because they are mutable; tuples can).
  • You want to communicate intent: "this sequence is fixed."

For more see the Python Tuples chapter.

set

A set is an unordered collection of unique items. Duplicate values are silently discarded on creation or addition.

# Duplicates are automatically removed
unique = {1, 2, 2, 3, 3, 3}
print(unique)  # {1, 2, 3}

# Adding an item
unique.add(4)
print(unique)  # {1, 2, 3, 4}

# Membership test — O(1) average
print(3 in unique)  # True

# Set operations
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)  # {1, 2, 3, 4}  union
print(a & b)  # {2, 3}        intersection
print(a - b)  # {1}           difference

When to use a set: when you need fast membership testing or want to eliminate duplicates from a collection. For more see the Python Sets chapter.

dict (Dictionary)

A dict is an unordered mapping of key-value pairs. As of Python 3.7 dictionaries preserve insertion order. Keys must be unique and immutable (strings and numbers are the most common choices).

person = {"name": "John", "age": 32, "city": "New York"}

# Access by key
print(person["name"])  # John

# Add a key
person["country"] = "United States"
print(person)
# {'name': 'John', 'age': 32, 'city': 'New York', 'country': 'United States'}

# Remove a key
del person["city"]
print(person)
# {'name': 'John', 'age': 32, 'country': 'United States'}

# Safe access with a default value
print(person.get("email", "not provided"))  # not provided

# Iterate over keys and values
for key, value in person.items():
    print(f"{key}: {value}")

When to use a dict: when data is naturally key-value structured and you need fast lookup by name. For more see the Python Dictionary Methods chapter.

NoneType

None is Python's null value — it represents the absence of a value. It is the only instance of NoneType.

result = None
print(result)         # None
print(type(result))   # <class 'NoneType'>

# Functions that do not explicitly return a value return None
def greet(name):
    print(f"Hello, {name}!")

x = greet("Alice")    # prints: Hello, Alice!
print(x)              # None

Always use is None (identity check) rather than == None (equality check):

if result is None:
    print("No result yet")

Mutability at a glance

Mutability determines whether a value can be changed in place after creation. This affects correctness (accidental aliasing), performance (copying vs. referencing), and what can be used as dict keys.

TypeMutable?Can be a dict key?
int, float, complexNoYes
strNoYes
boolNoYes
tupleNoYes (if all items immutable)
listYesNo
setYesNo
dictYesNo
NoneTypeNoYes

Type conversion

Python provides built-in functions to convert between types. This is called explicit type conversion (or casting).

# To int
print(int("42"))      # 42
print(int(3.9))       # 3  (truncates, does not round)
print(int(True))      # 1

# To float
print(float(7))       # 7.0
print(float("3.14"))  # 3.14

# To str
print(str(3.14))      # '3.14'
print(str(True))      # 'True'

# Between sequences
print(list((1, 2, 3)))   # [1, 2, 3]
print(tuple([1, 2, 3]))  # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3}

int() truncates (it does not round): int(3.9) gives 3, not 4. Use round() before int() if rounding is needed.

For a full discussion of casting rules see the Python Casting chapter.

Checking a type in your code

Use isinstance() (preferred) or type() for type checks:

x = 42
print(isinstance(x, int))    # True
print(isinstance(x, float))  # False

# isinstance also works with a tuple of types
print(isinstance(x, (int, float)))  # True

Prefer isinstance() over type(x) == int because it respects inheritance — a bool is also an int, so isinstance(True, int) returns True, which is usually what you want.

Quick-reference summary

TypeOrderedMutableDuplicatesLiteral syntax
intNo42
floatNo3.14
complexNo2+3j
strYesNoYes"hello"
boolNoTrue / False
listYesYesYes[1, 2, 3]
tupleYesNoYes(1, 2, 3)
setNoYesNo{1, 2, 3}
dictYes*YesKeys: No{"a": 1}
NoneTypeNoNone

* Insertion order preserved from Python 3.7+.

Practice

Practice
Which of the following are considered as immutable data types in Python?
Which of the following are considered as immutable data types in Python?
Was this page helpful?