When I started working with Python over a decade ago, one of the first things I had to understand was the concept of data types. This knowledge forms the foundation for everything you will ever build with Python.
Data types in Python categorize the type of value a variable can hold and determine the operations that can be performed on that data. Unlike other programming languages, Python is dynamically typed, so you don’t need to declare the type when creating variables.
In this tutorial, I’ll explain all the essential Python data types, providing clear examples so you can start building powerful applications immediately. Additionally, you will find numerous tutorials on useful data types in Python.
Before you go through each type, it helps to know which ones can change in place. Mutable vs Immutable in Python explains the difference, and Constants in Python shows how to name values that should not change.
Numeric Data Types in Python
Python Integers (int)
Integers in Python represent whole numbers without decimal points. They can be positive, negative, or zero. In Python, integers have unlimited precision, which means there’s no maximum or minimum value – they can be as large as your computer’s memory allows.
# Creating integer variables
employee_count = 157
annual_revenue = 5000000
temperature = -10
When working with integers, you can perform all standard arithmetic operations:
# Addition
total_employees = employee_count + 43 # 200
# Subtraction
remaining_budget = annual_revenue - 2500000 # 2500000
# Multiplication
double_revenue = annual_revenue * 2 # 10000000
# Division (returns float)
avg_revenue_per_employee = annual_revenue / employee_count # 31847.13
# Floor division (returns int)
avg_revenue_thousands = annual_revenue // 1000 # 5000
# Modulus (remainder)
remainder = 157 % 10 # 7
# Exponentiation
squared = employee_count ** 2 # 24649
Converting other data types to integers is straightforward using the int() function:
# String to integer
sales_string = "25000"
sales_integer = int(sales_string) # 25000
# Float to integer (truncates decimal part)
average_rating = int(4.7) # 4
# Boolean to integer
is_active = True
active_as_int = int(is_active) # 1 (True converts to 1, False to 0)
In real-world applications, I use integers for:
- Employee IDs and user identification
- Counting items in inventory
- Representing whole numbers in financial calculations
- Array/list indexing and slicing
- Representing dates and times (as timestamps)
- HTTP status codes in web applications
One important thing to note is that in Python 3, division between two integers (like 5/2) returns a float (2.5), unlike Python 2, where it would perform integer division. If you need integer division, use the floor division operator (//).
Integer-related tutorial:
- Convert Int to Bytes in Python
- Convert Int to Datetime Python
- How to Fix the TypeError: String Indices must be Integers Error in Python
- Print Strings and Integers Together in Python
- Check if a Number is an Integer in Python
- Check if a String is an Integer or Float in Python
- Check if a Variable Contains an Integer in Python
Number-related tutorials
- Swapping of Two Numbers in Python
- Armstrong Number using Recursion in Python
- Python Program to Find Armstrong Numbers in an Interval
- Check Armstrong Number in Python
- Get the First and Last Digit of a Number in Python
- Get the First Digit of a Number in Python
- Check N-Digit Armstrong Numbers in Python
- Program to Find a Perfect Number in Python
- Sum of Squares of Digits of a Number in Python
- Find the Sum of Two Numbers without Using Arithmetic Operators in Python
- Find the Sum of Even Digits in a Number in Python
- Python Program to Add N Numbers Accepted from the User
- Generate a 10-digit Random Number in Python
- Add Two Binary Numbers in Python
- Find the Sum of Prime Numbers in a Range in Python
- Python Program to Find the Product of Three Numbers
- Sum of Digits of a Number in Python
- Generate a Random Prime Number in Python
- Find the Next Largest Prime Number in Python
- Find Prime Numbers in a Range Using Python
- Check if a Number is Prime in Python
- Add Two Numbers in Python
- Get a Week Number from a Date in Python
- Subtract Number of Days from a Date in Python
- Extract Day Number of the Year from a Date in Python
- Generate Random 4-Digit Numbers in Python
- Check if a Python String Contains Only Numbers
- Floor a Number in Python
- Find Factors of a Number in Python
- Format Numbers as Currency in Python
- Convert Month Name to Number in Python
- Get Number of Months Between Two Dates in Python
- Calculate the Number of Days Between Two Dates in Python
- Convert Letters to Numbers in Python
- Pad Numbers with Leading Zeros in Python
- Check if Input is a Number in Python
- Floating Point Numbers in Python
- Count the Number of Digits in a Number in Python
- Split a Number into Digits in Python
- Round Numbers in Python
- Check if a Number is Even or Odd in Python
- Check if a String is Empty or NaN in Python
- Square a Number in Python
- Check if a Number is NaN in Python
- Generate Random Numbers Between 0 and 1 in Python
- Convert Decimal Numbers to Binary in Python
- Round Numbers to 2 Decimal Places in Python
- Generate Credit Card Numbers in Python for Testing
- Python Naming Conventions for Variables
- Reverse a Number in Python
- Factorial of a Number in Python
- Check if a String Represents a Number with Decimal in Python
- Check if a Number is an Integer in Python
- Python Program to Print Prime Numbers from 1 to 100
- Print Prime Numbers from 1 to N in Python
- Find the Largest and Smallest Numbers in Python
- Python Program to Divide Two Numbers
- Format Numbers with Commas in Python
Floats represent real numbers with decimal points or numbers in scientific notation. They’re essential for any calculation requiring precision beyond whole numbers.
For a practical integer exercise, finding the greatest common divisor (GCD) in Python uses math.gcd(), Euclid’s algorithm and NumPy for whole arrays.
Python integers have no fixed maximum, which surprises people coming from other languages. My post on the maximum value of int in Python explains sys.maxsize and where NumPy integers do overflow.
Python Floating-Point Numbers (float)
# Basic float examples
product_price = 49.99
tax_rate = 0.08
temperature = 98.6
scientific_notation = 6.022e23 # Avogadro's number
Floating-point operations mirror those available for integers:
# Basic arithmetic
total_price = product_price + (product_price * tax_rate) # 53.9892
discount_price = product_price * 0.9 # 44.991
# Rounding floats
rounded_price = round(product_price, 1) # 50.0
rounded_total = round(total_price, 2) # 53.99
# Converting temperature from Fahrenheit to Celsius
celsius = (temperature - 32) * 5/9 # 37.0
You can convert other data types to floats using the float() function:
# String to float
price_string = "19.99"
price_float = float(price_string) # 19.99
# Integer to float
count = 42
count_float = float(count) # 42.0
Floating-point precision issues are important to understand. Due to how computers represent decimal numbers in binary, some calculations may not be as precise as you’d expect:
print(0.1 + 0.2) # 0.30000000000000004 instead of exactly 0.3
For financial calculations or when precise decimal arithmetic is required, I use the decimal module:
from decimal import Decimal, getcontext
# Set precision
getcontext().prec = 4
# Exact decimal calculations
exact_sum = Decimal('0.1') + Decimal('0.2') # Decimal('0.3')
# Financial calculation
loan_amount = Decimal('10000.00')
interest_rate = Decimal('0.0325')
yearly_interest = loan_amount * interest_rate
print(yearly_interest) # Decimal('325.0')
In my work, I use floats for:
- Prices and financial calculations (with care)
- Scientific measurements and calculations
- Probabilities and statistical values
- Representing coordinates in graphics or mapping
- Time measurements with fractional parts
- Machine learning model parameters and metrics
Float-related tutorial:
- Convert Float to Int in Python
- Use Pandas to convert a float to an int in Python
- Check if a String is an Integer or Float in Python
- What are Floating Point Numbers in Python?
- Check if a Float Variable is Empty in Python
- Concatenate String and Float in Python
- Remove the Trailing Zeros from a Decimal in Python
- Remove Decimal Numbers in Python
- Print 2 Decimal Places in Python
- Concatenate String and Float in Python
For square roots, rounding up and down, factorials and constants like pi, see how to import math in Python and use it.
Sequence Data Types in Python
Python Strings (str)
Strings are sequences of characters, and they’re one of the most versatile data types in Python. They can be defined using single quotes ('), double quotes ("), or triple quotes (''' or """) for multi-line strings.
# Different ways to create strings
first_name = "Sarah"
last_name = 'Johnson'
address = """123 Main Street
New York, NY 10001"""
quote = 'She said, "Python is amazing!"'
Strings in Python are immutable, meaning once created, you cannot change their contents. Any operation that appears to modify a string creates a new string.
Accessing characters in strings is done via indexing, which starts at 0:
name = "Python"
first_char = name[0] # 'P'
last_char = name[-1] # 'n'
# Slicing gets a portion of the string
substring = name[1:4] # 'yth'
first_three = name[:3] # 'Pyt'
last_three = name[-3:] # 'hon'
reversed_string = name[::-1] # 'nohtyP'
Python offers powerful string methods that simplify text processing:
email = "SARAH.JOHNSON@EXAMPLE.COM"
# Case conversion
lower_email = email.lower() # 'sarah.johnson@example.com'
upper_name = first_name.upper() # 'SARAH'
title_case = "john smith".title() # 'John Smith'
# Finding and replacing
has_com = email.endswith('.COM') # True
position = email.find('JOHNSON') # 6
new_domain = email.replace('EXAMPLE.COM', 'COMPANY.ORG') # 'SARAH.JOHNSON@COMPANY.ORG'
# Splitting and joining
full_name = "Sarah J. Johnson"
name_parts = full_name.split() # ['Sarah', 'J.', 'Johnson']
comma_separated = ", ".join(name_parts) # 'Sarah, J., Johnson'
# Removing whitespace
username = " sarah_j "
clean_username = username.strip() # 'sarah_j'
# Checking content
is_alpha = first_name.isalpha() # True
is_numeric = "12345".isdigit() # True
starts_with = email.startswith('SARAH') # True
String formatting is essential for creating dynamic text:
# f-strings (Python 3.6+)
age = 32
message = f"{first_name} is {age} years old." # 'Sarah is 32 years old.'
# With formatting specifications
pi = 3.14159
formatted_pi = f"Pi to 2 decimal places: {pi:.2f}" # 'Pi to 2 decimal places: 3.14'
# format() method
template = "{} lives in {}, {}"
location = template.format(full_name, "New York", "NY") # 'Sarah J. Johnson lives in New York, NY'
# % operator (older style)
old_style = "%s has $%.2f in their account" % ("Sarah", 1234.56) # 'Sarah has $1234.56 in their account'
Strings are used in virtually every Python program for:
- User data and input processing
- File content manipulation
- Web content (HTML, JSON, XML)
- Database queries
- Configuration settings
- Output formatting and display
- Regular expression pattern matching
Python Lists
Python Lists are ordered, mutable collections that can contain items of any data type, including other lists. They’re one of Python’s most flexible data structures.
# Creating lists
empty_list = []
shopping_list = ["milk", "eggs", "bread", "apples", "coffee"]
mixed_list = [1, "hello", 3.14, True, [1, 2, 3]]
Lists offer numerous ways to access and modify their contents:
# Accessing elements by index
first_item = shopping_list[0] # 'milk'
last_item = shopping_list[-1] # 'coffee'
# List slicing
first_three = shopping_list[:3] # ['milk', 'eggs', 'bread']
middle_items = shopping_list[1:4] # ['eggs', 'bread', 'apples']
every_other = shopping_list[::2] # ['milk', 'bread', 'coffee']
# Modifying lists
shopping_list[0] = "almond milk" # Replace an item
shopping_list.append("cheese") # Add to the end
shopping_list.insert(1, "yogurt") # Insert at index 1
shopping_list.extend(["butter", "juice"]) # Add multiple items
popped_item = shopping_list.pop() # Remove and return the last item
shopping_list.remove("bread") # Remove first occurrence of 'bread'
# Finding items
bread_index = shopping_list.index("bread") # Find the index of 'bread'
coffee_count = shopping_list.count("coffee") # Count occurrences of 'coffee'
# Sorting and reversing
shopping_list.sort() # Sort in place alphabetically
shopping_list.sort(reverse=True) # Sort in descending order
shopping_list.reverse() # Reverse the list in place
# Sorted copy without modifying original
sorted_list = sorted(shopping_list)
# List comprehensions
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers] # [1, 4, 9, 16, 25]
even_squares = [n**2 for n in numbers if n % 2 == 0] # [4, 16]
Nested lists can be used to create multi-dimensional data structures:
# 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements in a 2D list
middle_element = matrix[1][1] # 5
List operations and built-in functions:
# Concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2 # [1, 2, 3, 4, 5, 6]
# Repetition
repeated = list1 * 3 # [1, 2, 3, 1, 2, 3, 1, 2, 3]
# List length
item_count = len(shopping_list)
# Min and max
lowest = min([10, 5, 23, 16]) # 5
highest = max([10, 5, 23, 16]) # 23
total = sum([10, 5, 23, 16]) # 54
# Checking if items exist in a list
has_apples = "apples" in shopping_list # True or False depending on list contents
Lists are extremely versatile in real-world Python applications. I use them for:
- Managing collections of user data (names, emails, etc.)
- Storing API response data for processing
- Tracking product inventory and details
- Creating data pipelines where items are processed sequentially
- Building navigation menus and UI elements in applications
- Storing historical data like price changes or user activity
- Managing task queues and processing workflows
Lists do have some performance considerations. While they’re excellent for general-purpose use, operations like insertion or deletion in the middle of large lists can be slow because all subsequent elements need to be shifted. For these cases, I sometimes use alternative data structures like collections.deque.
When working with large datasets, numpy arrays often provide better performance than standard Python lists, especially for numerical operations:
import numpy as np
# Creating a numpy array from a list
numpy_array = np.array([1, 2, 3, 4, 5])
squares = numpy_array ** 2 # Efficient element-wise operation: [1, 4, 9, 16, 25]
Boolean Data Type (bool)
The Boolean data type represents one of two values: True or False. These values are essential for controlling program flow, making decisions, and evaluating conditions.
# Basic boolean values
is_logged_in = True
has_premium_account = False
Booleans result from comparison operations:
# Comparison operators
age = 25
is_adult = age >= 18 # True
is_senior = age >= 65 # False
names_match = "Sarah" == "sarah" # False (case-sensitive)
Boolean logic operations allow you to combine conditions:
# Logical operators
can_access_premium = is_logged_in and has_premium_account # False
can_view_content = is_logged_in or has_premium_account # True
is_regular_user = not has_premium_account # True
# Complex conditions
is_target_demographic = (age >= 18 and age <= 35) and is_logged_in # True
In Python, all objects have an implicit boolean value that can be used in conditional statements:
# Truthy and falsy values
empty_string = ""
if not empty_string: # Empty strings are falsy
print("Please enter your name")
user_list = []
if not user_list: # Empty lists are falsy
print("No users found")
# Common falsy values
# False, None, 0, 0.0, "", [], {}, set()
# Everything else is truthy
non_zero = 42
if non_zero: # Non-zero numbers are truthy
print("Value exists")
You can convert other types to Boolean using the bool() function:
# Converting to boolean
print(bool(0)) # False
print(bool(42)) # True
print(bool("")) # False
print(bool("Hello")) # True
print(bool([])) # False
print(bool([1, 2])) # True
In my development work, booleans are crucial for:
- User authentication logic
- Access control and permissions
- Form validation
- Feature flags and toggles
- Data filtering criteria
- Error handling and exception control
- Conditional UI rendering
- Testing assertions and conditions
Understanding Boolean logic is fundamental to writing effective conditional statements and creating robust program flow.
Boolean-related tutorial:
- Convert Bool to Int in Python
- Check if a String is a Boolean Value in Python
- Check if a Variable is a Boolean in Python
Dictionary Data Type (dict)
Python Dictionaries are incredibly versatile key-value stores that allow you to create mappings between keys and their associated values. Unlike sequences that are indexed by numbers, dictionaries use keys (typically strings) to access values.
# Creating dictionaries
empty_dict = {}
user = {
"id": 12345,
"username": "sarah_j",
"email": "sarah.j@example.com",
"is_active": True,
"age": 32
}
# Nested dictionaries
customer = {
"name": "John Smith",
"orders": {
"2023-01-15": {"item": "Laptop", "price": 1299.99},
"2023-03-20": {"item": "Headphones", "price": 149.95}
},
"preferences": {
"notifications": True,
"theme": "dark"
}
}
Accessing and manipulating dictionary data is straightforward:
# Accessing values
print(user["username"]) # 'sarah_j'
# Using get() for safe access (returns None or default if key doesn't exist)
print(user.get("location")) # None
print(user.get("location", "Unknown")) # 'Unknown'
# Adding or updating values
user["phone"] = "555-123-4567"
user["age"] = 33 # Updates existing key
# Removing items
removed_email = user.pop("email") # Removes and returns the value
del user["age"] # Removes the key-value pair
# Checking if a key exists
has_username = "us