When you start programming in Python, you quickly realize you need to store many kinds of information. Numbers, text, product lists, user records. Each data type has its own characteristics that define exactly how you can use it in your code. Understanding these types is essential if you want to write programs that actually work as expected.
In this complete guide, you will learn everything about the main data types in Python. We will walk through integers, decimals, text, lists, and dictionaries. With direct, practical examples, you will master each type and know exactly when to reach for it.
What Are Data Types in Python
Data types represent the different categories of values you can work with in Python. Each type comes with its own operations and behavior. A number supports mathematical calculations. A piece of text supports character manipulation. A list stores multiple values in a single sequence.
Python uses dynamic typing. That means you never have to declare the type of a variable before using it. Python figures out automatically which type of data you are storing. When you write age = 25, Python understands that age is an integer.
To check the type of any variable, use the type() function. It returns the exact type of the data. For example, type(25) returns <class 'int'>, confirming that 25 is an integer. This flexibility makes Python easier to learn, but it also means you need to pay attention so you don’t accidentally mix incompatible types.
Int: Working with Integers in Python
The int type represents whole numbers in Python. These are values with no decimal places, whether positive or negative. Use int to count things, represent ages, years, or any discrete quantity. Any number written without a decimal point is automatically treated as an int.
Examples of integers: 10, -5, 0, 1000000. You can perform basic math operations with them: addition, subtraction, multiplication, division. Dividing two integers can still produce a float if there is a remainder.
quantity = 50
temperature = -10
birth_year = 1990
result = quantity + 20 # 70
doubled = quantity * 2 # 100Python has no limit on the size of integers. You can work with extremely large numbers without any special handling. Unlike other languages that cap integer size, Python manages the required memory automatically. This makes int very flexible for scientific and financial calculations.
To convert other types into int, use the int() function. It transforms numeric strings or floats into integers. Watch out though: when converting a float to int, Python simply truncates the decimal part instead of rounding it. For instance, int(9.9) results in 9, not 10.
Float: Decimal and Floating-Point Numbers
The float type stores numbers with decimal places. Use float whenever you need fractional precision: prices, measurements, scientific calculations, percentages. Any number written with a decimal point is automatically a float.
Common float examples: 3.14, -0.5, 2.0, 99.99. Even round numbers like 5.0 are floats if written with a decimal point. The presence of the point defines the type, not the value itself.
price = 49.90
height = 1.75
tax_rate = 0.05
total = price * (1 + tax_rate) # 52.395
average = (8.5 + 9.0 + 7.5) / 3 # 8.333...Floats can carry small imprecisions because of how computers store decimal numbers internally. This is completely normal and happens in every programming language, not just Python. For work that demands exact precision, such as financial calculations, use Python’s built-in decimal module instead.
You can convert an int or a string into a float using float(). For example, float("3.14") turns the string into a decimal number. Operations between an int and a float always result in a float. If you add 5 + 2.0, the result will be 7.0.
Str: Working with Text and Strings
The str type represents text and character sequences. Use strings to store names, messages, descriptions, or any textual information. Strings in Python are always delimited by single or double quotes.
You can create strings in several ways: "Hello", 'Python', """Long text""". Triple quotes allow text that spans multiple lines. Choosing single or double quotes is up to you, just stay consistent throughout your code.
name = "Maria Silva"
message = 'Welcome to Python'
description = """This is a text
that spans several lines
in the code"""
greeting = "Hello, " + name # ConcatenationStrings in Python are immutable. You cannot change individual characters after creating a string. To modify text, you create a brand new string instead. Python offers plenty of useful string methods: upper(), lower(), replace(), split().
You can access individual characters using indexes: name[0] returns the first character. Use slicing to extract parts of a string: name[0:5] returns the first five characters. To convert other types into a string, use str(). For instance, str(25) turns the number into text.
List: Storing Multiple Values in Sequence
The list type lets you store multiple values in a single variable. Lists are ordered, mutable, and allow duplicate elements. Use lists whenever you need to group related data that might change while the program runs.
Create lists using square brackets: numbers = [1, 2, 3]. Lists can hold any type of data, and you can even mix numbers, text, and other lists inside a single list. This flexibility is what makes lists so versatile.
fruits = ["apple", "banana", "orange"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "text", 3.14, True]
first = fruits[0] # "apple"
last = fruits[-1] # "orange"Lists are mutable. You can add, remove, or modify elements after creating the list. Use append() to add an item to the end, insert() to add one at a specific position, and remove() to delete an element by its value.
Access elements by index: numbers[0] returns the first element. Negative indexes count from the end: numbers[-1] returns the last one. Use a for loop to iterate over every element. Lists also support operations like sorting, reversing, and counting.
Dict: Organizing Data with Dictionaries
The dict type stores data as key-value pairs. Dictionaries are ideal for representing more complex data structures. Use dict whenever you need to associate related pieces of information, such as user records or configuration settings.
Create dictionaries using curly braces: person = {"name": "John", "age": 30}. Every key must be unique, while values can be of any type. You access values through their key, not through a numeric position.
user = {
"name": "Anna Costa",
"email": "[email protected]",
"age": 28,
"active": True
}
user_name = user["name"] # "Anna Costa"Dictionaries are mutable. You can add, modify, or remove key-value pairs at any time. Use keys() to get every key, values() to get every value, and items() to get key-value pairs together.
Trying to access a key that does not exist raises an error. To avoid this, use the get() method instead: user.get("phone", "Not provided"). This returns a fallback value when the key is missing. Dictionaries are fundamental when working with JSON data.
Converting Between Data Types
Python lets you convert values between different types. This process is called type conversion, or casting. Use the int(), float(), and str() functions to transform data as needed.
Convert a string into a number: number = int("42"). The string must contain only valid digits, otherwise Python raises an error. Always validate your data before converting it.
# String to number
text = "100"
number = int(text) # 100
decimal = float("3.14") # 3.14
# Number to string
age = 25
age_text = str(age) # "25"
# Float to int (truncates, does not round)
rounded_down = int(9.9) # 9When converting a float to int, Python truncates the decimal part with no automatic rounding. If you need to round instead, use the round() function before converting. For example, int(round(9.7)) results in 10.
Lists and dictionaries can also be converted from other iterables in certain cases. Use list() to turn other iterables into lists, and dict() to build a dictionary from tuples of pairs. Understanding these conversions helps you handle data coming from different sources.
Comparing Python’s Core Data Types
Every data type has unique characteristics that determine when you should use it. Integers are great for counts and exact values. Floats handle measurements that need decimal precision. Strings hold any kind of textual information.
Lists store ordered collections that can change over time. Dictionaries organize related data as key-value pairs. Picking the right type makes your code both more efficient and easier to read.
| Type | Mutable | Ordered | Main Use |
|---|---|---|---|
| int | No | N/A | Whole numbers |
| float | No | N/A | Decimal numbers |
| str | No | Yes | Text |
| list | Yes | Yes | Ordered collections |
| dict | Yes | No* | Key-value pairs |
*Dictionaries have preserved insertion order since Python 3.7, but they are still not indexed by numeric position.
Immutable types like int, float, and str cannot be changed after creation, every modification creates a brand new object. Mutable types like list and dict allow you to change the same object in place. This difference affects how you work with each type day to day. You can read more about the official behavior in the Python documentation on built-in types.
Common Operations for Each Type
Every data type supports its own set of operations. Numbers support standard math operators: addition, subtraction, multiplication, division. Strings support concatenation with the + operator. Lists support adding elements and sorting.
For integers and floats, use the standard arithmetic operators. Division always returns a float, even between two integers. Use // for integer (floor) division, % for the remainder, and ** for exponentiation.
# Operations with numbers
total = 10 + 5 # 15
division = 10 / 3 # 3.333...
floor_division = 10 // 3 # 3
remainder = 10 % 3 # 1
power = 2 ** 3 # 8
# Operations with strings
name = "python"
upper_name = name.upper() # "PYTHON"Strings also support several useful manipulation methods. Use upper() and lower() to change letter casing, strip() to remove extra whitespace, split() to break text into a list, and replace() to swap out parts of a string.
Checking Data Types
Checking the type of a variable helps you avoid bugs before they happen. Use the type() function to discover the exact type, and isinstance() to check whether a value belongs to a specific type. This practice becomes essential whenever you are working with user input.
age = 25
print(type(age)) # <class 'int'>
price = 19.90
print(type(price)) # <class 'float'>
name = "Python"
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
print(isinstance(name, (int, str))) # TrueThe isinstance() function accepts a tuple of types, which lets you check multiple types at once. This is generally safer than comparing type() directly, since it also accounts for inheritance. See the official reference for isinstance() in the Python documentation.
Understanding these types helps you debug code faster. Many bugs happen when incompatible types get mixed together, like trying to add a string to a number. Checking types before critical operations prevents these failures before they reach production.
Best Practices with Data Types
Use the most appropriate type for each situation. Do not store numbers as strings if you plan to run calculations on them. Do not use a list when you actually need descriptive keys. Choosing the correct type keeps your code clearer and more efficient.
Avoid mixing types unnecessarily and keep your data structures consistent. If a list is meant to hold only numbers, do not slip strings into it. This makes error handling and future maintenance much easier.
- Validate data before converting between types
- Use type hints to document expected types
- Prefer dictionaries for structured data
- Use lists for collections of similar items
- Choose descriptive variable names that hint at the type
- Document expected types in functions
Take advantage of Python’s dynamic typing without overusing it. In larger projects, consider adopting type hints. They do not affect execution, but they help code editors catch mistakes early. For example: def calculate(x: int, y: int) -> int:. You can learn more in PEP 484, the specification that introduced type hints.
Practical, Everyday Examples
Let’s see how these data types show up in real programming situations. These examples reflect the kind of practical applications you will run into in real projects.
Simple Registration System
# Product registration using a dictionary
product = {
"name": "Notebook",
"price": 2999.90,
"stock": 15,
"categories": ["Electronics", "Computers"]
}
name = product['name']
price = product['price']
in_stock = product['stock'] > 0
print(f"Product: {name}")
print(f"Price: ${price:.2f}")
print(f"In stock: {in_stock}")Calculating a Grade Average
# Storing grades in a list
grades = [8.5, 7.0, 9.0, 6.5, 8.0]
# Calculating the average
average = sum(grades) / len(grades)
print(f"Average: {average:.2f}")
# Checking whether the student passed
passed = average >= 7.0
print(f"Passed: {passed}")Processing a Shopping List
# Shopping list with prices
cart = [
{"item": "Rice", "price": 25.90, "quantity": 2},
{"item": "Beans", "price": 8.50, "quantity": 3},
{"item": "Milk", "price": 5.20, "quantity": 6},
]
total = sum(product["price"] * product["quantity"] for product in cart)
print(f"Cart total: ${total:.2f}")These examples show how combining different data types solves real-world problems: dictionaries organize related fields, lists store multiple values, and numbers power precise calculations.
Frequently Asked Questions (FAQ)
1. What is the difference between int and float in Python?
Int represents whole numbers with no decimal places, while float stores numbers with decimal places and greater precision for fractional values.
2. Can I mix different types inside a single list?
Yes, Python allows lists with mixed types, but it is generally not recommended if you want to keep your code organized and predictable.
3. How do I convert a string into a number in Python?
Use int() to convert to a whole number or float() to convert to a decimal. Example: number = int(“42”).
4. What happens when you add an int and a float together?
The result is always a float. Python automatically converts the int into a float before performing the operation.
5. Are strings mutable in Python?
No, strings are immutable. Any modification creates a brand new string in memory instead of changing the original.
6. When should I use a list instead of a dictionary?
Use a list for ordered collections of similar items. Use a dictionary when you need to associate keys with specific values.
7. How do I check if a variable is a string?
Use isinstance(variable, str), which returns True if the value is a string, or type(variable) to inspect the exact type.
8. Can I use numbers as dictionary keys?
Yes, any immutable type can be used as a dictionary key, including numbers and tuples.
9. What does dynamic typing mean in Python?
It means Python automatically identifies a variable’s type without requiring you to declare it beforehand.
10. How do I create an empty list in Python?
Use empty square brackets, list = [], or the list() function, list = list().






