Python Data Types: Every Type Explained with Code Examples (2026)
Python has 14 built-in data types organised into six categories: numeric (int, float, complex), sequence (str, list, tuple, range), mapping (dict), set (set, frozenset), Boolean (bool), and None (NoneType). Choosing the correct type for each variable prevents the majority of beginner errors and makes code significantly more efficient.
Best GenAI & Machine Learning Course - Enroll Now!
Quick reference: All Python data types
| Category | Data Types | Mutable | Use When |
|---|---|---|---|
| Numeric | int, float, complex | No | You need numbers for counts, measurements, or calculations |
| Sequence | str, list, tuple, range | str/tuple/range: No; list: Yes | You need ordered collections like text, lists of items, or indexable ranges |
| Mapping | dict | Yes | You need key–value pairs, such as labeled or JSON-style data |
| Set | set, frozenset | set: Yes; frozenset: No | You need unique values or mathematical set operations |
| Boolean | bool | No | You need True/False conditions for decisions and logic |
| None | NoneType | No | You need to represent “no value”, “not yet set”, or “not found” |
# Python identifies the type from the value you assign
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
Python is dynamically typed, meaning you do not declare types explicitly. Python infers the type from the value you assign. This makes Python faster to write than statically typed languages, but it does require awareness of which type each variable holds at each point in your code.
Must Read: Python for AI: A Complete Beginner's Guide to Building AI with Python
Numeric Data Types in Python
Python supports three numeric data types: int for whole numbers, float for decimal numbers, and complex for numbers with real and imaginary parts.
Integer (int)
Integers are whole numbers with no decimal point, positive, negative, or zero. Python integers have unlimited precision: unlike C or Java which restrict integers to 32-bit or 64-bit, Python automatically adjusts memory allocation and can handle arbitrarily large integers without overflow.
students_in_class = 45
temperature_delhi = -2
floors_in_building = 0
very_large_number = 9999999999999999999999 # Python handles this without overflow
print(type(students_in_class)) # <class 'int'>
Use int for counts, scores, indices, or any quantity that must always be a whole number. When you need to use an integer inside a string, convert it with str() first.
marks = 95
# print("Your marks are: " + marks) # TypeError: can only concatenate str to str
print("Your marks are: " + str(marks)) # Your marks are: 95
print(f"Your marks are: {marks}") # Your marks are: 95 (f-strings handle this automatically)
Float (float)
Floats are numbers with a decimal point. Python uses 64-bit double precision floating-point representation following the IEEE 754 standard.
price = 299.99
pi = 3.14159
average_score = 87.5
print(type(price)) # <class 'float'>
print(10 / 2) # 5.0 (division always returns float in Python 3)
print(10 // 2) # 5 (floor division returns int)
print(0.1 + 0.2) # 0.30000000000000004 (floating-point precision limitation)
The 0.1 + 0.2 result is a known floating-point arithmetic limitation. For financial calculations requiring exact decimal precision, use the decimal module instead.
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2")) # 0.3 (exact)
Complex (complex)
Complex numbers have a real and an imaginary part, written using j for the imaginary unit.
z = 3 + 5j
print(type(z)) # <class 'complex'>
print(z.real) # 3.0
print(z.imag) # 5.0
print(abs(z)) # 5.830951894845301 (magnitude)
Complex numbers are primarily used in scientific computing, signal processing, and electrical engineering applications.
Also Read: AI Programming Languages: Python, R and What to Learn for AI in 2026
String Data Type (str)
Strings store text of any length: names, messages, file paths, user input, and configuration values. In Python, strings are immutable sequences of Unicode characters.
name = "Priya"
city = 'Lucknow'
message = "Welcome to EICTA Consortium"
paragraph = """This is a
multi-line string."""
print(type(name)) # <class 'str'>
Common string methods:
course = "digital marketing"
print(course.upper()) # DIGITAL MARKETING
print(course.capitalize()) # Digital marketing
print(course.replace("digital", "advanced")) # advanced marketing
print(len(course)) # 18
print(course.split(" ")) # ['digital', 'marketing']
print(course.strip()) # removes leading/trailing spaces
print(course.startswith("digital")) # True
print(course.count("i")) # 2
String formatting: f-strings (the modern approach):
student = "Rahul"
score = 92
print(f"Student: {student}, Score: {score}") # Student: Rahul, Score: 92
print(f"Score rounded: {score:.1f}") # Score rounded: 92.0
F-strings, introduced in Python 3.6, are the preferred string formatting method in 2026 because they are the most readable and fastest at runtime.
Read More: AI in Fintech: Applications, Companies and Use Cases 2026
Boolean Data Type (bool)
A Boolean holds exactly one of two values: True or False. Booleans power every conditional decision in Python.
is_enrolled = True
has_paid_fees = False
age = 20
print(age >= 18) # True
print(age == 25) # False
print(age != 25) # True
Conditional logic:
marks = 85
if marks >= 60:
print("Pass")
else:
print("Fail")
Truthy and falsy values:
Python evaluates non-Boolean values as True or False in conditional contexts.
print(bool(0)) # False
print(bool(1)) # True (any non-zero number)
print(bool("")) # False
print(bool("hello")) # True (any non-empty string)
print(bool([])) # False
print(bool([1, 2])) # True (any non-empty collection)
print(bool(None)) # False
Values that evaluate as False: 0, 0.0, "", [], {}, set(), tuple(), and None. Everything else evaluates as True.
NoneType (None)
None is Python's way of representing "no value" or "not applicable." It has its own type, NoneType, and is not equivalent to 0, False, or an empty string.
result = None
print(type(result)) # <class 'NoneType'>
user_input = None # declared but not yet assigned
if result is None:
print("No result found")
Always use is None and is not None to check for None rather than == None. This is more reliable and follows Python convention.
# Correct
if result is None:
print("Empty")
# Incorrect (works but not recommended)
if result == None:
print("Empty")
None is commonly used as a default parameter value in functions, as a return value when a function finds nothing, and as a placeholder for variables that will be assigned later.
List (list)
A list is an ordered, mutable collection that can hold values of any type, including mixed types.
subjects = ["Python", "Data Science", "Machine Learning"]
scores = [85, 92, 78, 95]
mixed = ["Arjun", 21, True, 9.5]
Accessing and modifying items:
fruits = ["mango", "banana", "apple"]
print(fruits[0]) # mango (indexing starts at 0)
print(fruits[-1]) # apple (negative index counts from end)
print(fruits[0:2]) # ['mango', 'banana'] (slicing)
fruits.append("grapes") # add to end
fruits.insert(1, "papaya") # insert at specific position
fruits.remove("banana") # remove first occurrence
popped = fruits.pop() # remove and return last item
fruits[0] = "watermelon" # update value at index
print(len(fruits)) # number of items
print(sorted(fruits)) # return sorted list (does not modify original)
Use a list when order matters and you expect to add, remove, or update items.
Tuple (tuple)
A tuple is an ordered, immutable collection. Once created, you cannot change, add, or remove items.
coordinates = (28.61, 77.21)
birthday = (15, "August", 2001)
rgb_color = (255, 128, 0)
# Tuple unpacking
name, age, city = ("Neha", 22, "Mumbai")
print(name) # Neha
print(age) # 22
point = (10, 20)
# point[0] = 99 # TypeError: 'tuple' object does not support item assignment
# Single-element tuple: requires trailing comma
single = (42,) # this is a tuple
not_tuple = (42) # this is just the integer 42
print(type(single)) # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>
Use tuples for data that should not change: coordinates, colour values, database records, and function return values where multiple values are returned together.
Performance note: Tuples are faster than lists for iteration and consume less memory, making them preferable when immutability is acceptable.
Set (set)
A set stores unique values with no guaranteed order. Duplicate values are automatically removed.
enrolled_students = {"Amit", "Priya", "Rahul", "Priya"}
print(enrolled_students) # {'Amit', 'Priya', 'Rahul'} (duplicate removed)
Set operations:
batch_a = {1, 2, 3, 4, 5}
batch_b = {4, 5, 6, 7, 8}
print(batch_a | batch_b) # {1, 2, 3, 4, 5, 6, 7, 8} union
print(batch_a & batch_b) # {4, 5} intersection
print(batch_a - batch_b) # {1, 2, 3} difference
print(batch_a ^ batch_b) # {1, 2, 3, 6, 7, 8} symmetric difference
You cannot access set items by index because sets are unordered. Use sets when you need to remove duplicates, test membership efficiently, or perform mathematical set operations.
frozenset is the immutable version: once created, you cannot add or remove items. It is used where a set needs to be hashable, such as when using it as a dictionary key.
Dictionary (dict)
A dictionary stores key-value pairs. Keys must be unique and immutable (strings, numbers, or tuples). Values can be any type.
student = {
"name": "Vikram",
"age": 20,
"city": "Bengaluru",
"enrolled": True
}
print(student["name"]) # Vikram
print(student.get("grade", "Not set")) # Not set (safe access with default)
student["course"] = "Data Science" # add new key
student["age"] = 21 # update existing value
del student["city"] # remove a key
for key, value in student.items():
print(f"{key}: {value}")
# Check if key exists
if "name" in student:
print("Name found")
Dictionary comprehension:
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionaries are used everywhere in Python: API responses, configuration objects, JSON data, and anywhere structured labeled data is needed.
Type Hints: Writing More Readable Python Code
Type hints, introduced in Python 3.5 and significantly improved in Python 3.10 and 3.12, allow you to annotate variable and function types without changing runtime behaviour. They are not enforced by Python itself but are used by code editors, linters, and static analysis tools to catch type errors before runtime.
# Variable type hints
age: int = 20
name: str = "Priya"
score: float = 94.5
is_active: bool = True
# Function type hints
def calculate_grade(marks: int) -> str:
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
else:
return "C"
# Collection type hints (Python 3.9+)
def get_subjects() -> list[str]:
return ["Python", "Machine Learning", "Data Science"]
def get_student_record() -> dict[str, int]:
return {"Rahul": 92, "Priya": 88}
In 2026, type hints are considered best practice in professional Python code because they make code self-documenting and allow tools like mypy, Pyright, and VS Code's IntelliSense to catch errors at development time rather than runtime.
Type Conversion (Casting)
Type conversion changes a value from one type to another using built-in functions: int(), float(), str(), list(), bool(), and tuple().
# String to int (string must contain a valid integer)
age_string = "25"
age_int = int(age_string) # 25
# Int to string
roll = 1042
roll_string = str(roll) # "1042"
# Int to float
marks = 85
marks_float = float(marks) # 85.0
# Float to int (truncates toward zero, does not round)
price = 299.99
price_int = int(price) # 299 (not 300)
# String to list
sentence = "Python is powerful"
words = sentence.split(" ") # ['Python', 'is', 'powerful']
# List to set (removes duplicates)
names = ["Amit", "Priya", "Amit", "Rahul"]
unique_names = set(names) # {'Amit', 'Priya', 'Rahul'}
# Bool conversion
print(int(True)) # 1
print(int(False)) # 0
print(float(True)) # 1.0
When you encounter a TypeError about mixing types, a type conversion is almost always the correct fix.
Complete Comparison: All Python Data Types
| Data Type | Class | Mutable | Ordered | Duplicates | Example |
|---|---|---|---|---|---|
| Integer | int | No | N/A | N/A | 25 |
| Float | float | No | N/A | N/A | 99.9 |
| Complex | complex | No | N/A | N/A | 3+5j |
| String | str | No | Yes | Yes | "Hello" |
| Boolean | bool | No | N/A | N/A | True |
| List | list | Yes | Yes | Yes | [1, 2, 3] |
| Tuple | tuple | No | Yes | Yes | (1, 2, 3) |
| Set | set | Yes | No | No | {1, 2, 3} |
| Frozenset | frozenset | No | No | No | frozenset({1, 2}) |
| Dictionary | dict | Yes | Yes | Keys: No | {"a": 1} |
| Range | range | No | Yes | Yes | range(0, 10) |
| None | NoneType | No | N/A | N/A | None |
How to Choose the Right Data Type
- Use int for counts, IDs, and whole-number scores
- Use float for prices, percentages, and measurements; use Decimal for exact financial calculations
- Use str for any text data
- Use bool for conditions, flags, and toggles
- Use list when order matters and the collection will change
- Use tuple for ordered data that must not change; prefer over lists when immutability is acceptable for better performance
- Use set for unique values or mathematical set operations
- Use frozenset when you need a hashable set (for use as dictionary keys)
- Use dict for labeled or structured data
- Use None when there is no value yet or to indicate "not found"
- Use type hints to document expected types in function signatures and complex variable assignments
Common Beginner Mistakes with Python Data Types
Forgetting that indexing starts at 0, not 1. fruits[0] is the first item, not fruits[1].
Creating a single-element tuple incorrectly. (42) is just the integer 42. You need a trailing comma: (42,).
Trying to modify a tuple. Tuples are immutable by design. If you need to modify the collection, use a list.
Adding numbers directly to strings. "Your score: " + 95 raises a TypeError. Use str(95) or an f-string.
Assuming sets maintain insertion order. Sets are unordered. Do not rely on print order being consistent.
Using == None instead of is None. Always use is None for checking None values.
Float precision in financial calculations. 0.1 + 0.2 does not equal 0.3 in Python. Use the decimal module for money.
Mutable default arguments in functions. Using a mutable type like a list as a default argument creates a shared object across all calls. Use None as the default and create the list inside the function.
# Wrong
def add_item(item, collection=[]):
collection.append(item)
return collection
# Correct
def add_item(item, collection=None):
if collection is None:
collection = []
collection.append(item)
return collection
Frequently Asked Questions
What are all the data types in Python?
Python has 14 built-in data types in six categories. Numeric: int, float, complex. Sequence: str, list, tuple, range. Mapping: dict. Set: set, frozenset. Boolean: bool. None: NoneType. For most everyday programming, you will primarily work with int, float, str, bool, list, dict, and None.
What is the difference between a list and a tuple in Python?
Both are ordered sequences that can hold values of any type. The key difference is mutability: lists are mutable (you can add, remove, or modify items after creation) while tuples are immutable (you cannot change them after creation). Tuples are also faster than lists and can be used as dictionary keys because they are hashable. Use a list when the data will change; use a tuple when the data is fixed.
What is dynamic typing in Python?
Dynamic typing means Python determines a variable's type from its value at runtime rather than requiring you to declare the type explicitly in the code. x = 42 makes x an integer without you writing int x = 42. You can also reassign a different type to the same variable: x = "hello" is valid in Python. Dynamic typing makes Python faster to write but requires careful attention to what type each variable holds at each point in your program.
Why does 0.1 + 0.2 not equal 0.3 in Python?
This is a floating-point arithmetic precision limitation that affects most programming languages, not just Python. Float values are stored in binary (base 2), and some decimal fractions like 0.1 cannot be represented exactly in binary, leading to small rounding errors. For code where exact decimal precision is required, such as financial calculations, use from decimal import Decimal and work with Decimal("0.1") and Decimal("0.2") instead.
What are type hints in Python and should beginners learn them?
Type hints are optional annotations that indicate the expected data type of a variable or function parameter and return value. They do not affect how Python runs the code but allow code editors and static analysis tools to detect type errors before runtime. In 2026, type hints are considered best practice in professional Python code. Beginners should understand what they mean when they encounter them in other people's code, and start incorporating them into their own functions as they become comfortable with the basics.
What is the difference between None and False or 0 in Python?
None, False, and 0 all evaluate as False in a boolean context, but they represent fundamentally different concepts. None means the complete absence of a value: no data, not applicable, not yet assigned. False is a boolean value representing logical falsity. 0 is a numeric value representing zero. Always use is None to check for the absence of a value rather than relying on the falsy behaviour of None in a conditional.



