Practical examples of examples of basic data types in Python
Let’s start with concrete code. Here are short, realistic examples of basic data types in Python that you’ll see in almost every beginner project:
## Integer: counting users
active_users = 128
## Float: average rating
average_rating = 4.7
## String: username
username = "alex_smith_92"
## Boolean: feature flag
is_premium_user = True
## List: shopping cart items
cart_items = ["laptop", "mouse", "USB-C cable"]
## Tuple: immutable GPS coordinates
office_location = (40.7128, -74.0060)
## Set: unique tags
post_tags = {"python", "tutorial", "beginner"}
## Dictionary: user profile
user_profile = {
"id": 501,
"name": "Alex Smith",
"email": "alex@example.com",
"is_active": True,
}
These are the best examples to keep in your mental toolbox because they mirror real apps: user counts, ratings, settings, and profile data. Now let’s unpack each one with more examples of examples of basic data types in Python, and see how they behave.
Integers and floats: examples include money, scores, and measurements
When people ask for examples of basic data types in Python, integers and floats are usually first on the list.
Integer examples in everyday Python code
Integers (int) are whole numbers: negative, zero, or positive. Think counts, IDs, and loop counters.
## Example of tracking a score in a game
score = 0
score += 10 # player earns 10 points
score -= 3 # penalty
## Example of user ID from a database
user_id = 1042
## Example of page number in pagination
current_page = 5
A few more real examples:
- Tracking remaining lives in a game (
lives = 3) - Counting failed login attempts (
failed_attempts = 2) - Storing year values (
year_joined = 2024)
These examples of integers show up constantly in APIs, database IDs, and loop logic.
Float examples: prices, temperatures, percentages
Floats (float) are numbers with decimals. They’re used for anything that might not be a whole number.
## Example of a product price
price = 19.99
## Example of a temperature in Fahrenheit
temperature_f = 72.5
## Example of a discount rate
discount_rate = 0.15 # 15%
final_price = price * (1 - discount_rate)
More real examples include:
- Average session time in minutes (
avg_session_minutes = 7.34) - BMI or health metrics in a health app (
bmi = 24.7) - Conversion rates in analytics (
conversion_rate = 0.034)
For a deeper look at numeric behavior (including floating point quirks), the official Python tutorial from the Python Software Foundation is a solid reference: https://docs.python.org/3/tutorial/introduction.html
Strings: examples of text data in Python apps
Strings (str) are for text: names, messages, JSON snippets, even small pieces of HTML.
Example of formatting user-facing messages
first_name = "Alex"
notifications = 3
welcome_message = f"Hi {first_name}, you have {notifications} new notifications."
print(welcome_message)
## Output: Hi Alex, you have 3 new notifications.
Examples include cleaning and normalizing text
raw_username = " Taylor.SMITH "
normalized = raw_username.strip().lower().replace(" ", "_")
print(normalized)
## Output: taylor.smith
More real examples of working with strings:
- Parsing CSV lines from a file
- Building search queries from user input
- Logging messages for debugging
Even in data-heavy fields like health or education, strings matter. For instance, a health-tracking app might store symptom descriptions as strings while numeric values handle vitals like heart rate. For general health information, sites like Mayo Clinic (https://www.mayoclinic.org) and WebMD (https://www.webmd.com) are commonly used by developers to understand the domain they’re modeling, even though the code itself lives in Python.
Booleans: simple yes/no flags powering logic
Booleans (bool) store True or False. They’re tiny, but they control big decisions in your code.
Example of access control
is_admin = False
is_premium_user = True
if is_admin or is_premium_user:
print("Access granted to premium dashboard")
else:
print("Upgrade required")
Examples include feature flags and validation checks
email = "alex@example.com"
has_at_symbol = "@" in email
ends_with_com = email.endswith(".com")
is_valid_email_guess = has_at_symbol and ends_with_com
You’ll see booleans everywhere: toggling dark mode, enabling beta features, or deciding whether to show error messages. When people look for examples of examples of basic data types in Python that control flow, booleans are usually the star.
Lists: the workhorse collection type
Lists (list) hold ordered, changeable collections of items. They’re flexible and used constantly.
Example of a to-do list app
todos = ["Write report", "Review PRs", "Plan sprint"]
## Add a new task
todos.append("Refactor billing module")
## Mark the first task as done
done_task = todos.pop(0)
print("Completed:", done_task)
print("Remaining:", todos)
Best examples of lists in real Python code
Examples include:
- Search results (
search_results = [result1, result2, result3]) - Sensor readings over time (
temperatures = [98.6, 98.7, 99.1]) - Rows from a database query (
rows = cursor.fetchall()often returns a list)
In health or education analytics, you might see lists of test scores, daily step counts, or survey responses. A simple example of analyzing a list of temperatures:
temps_f = [72.5, 70.0, 68.9, 71.2]
avg_temp = sum(temps_f) / len(temps_f)
print("Average temp:", avg_temp)
Tuples: ordered, but locked in place
Tuples (tuple) are like lists, but immutable. Once created, they can’t be changed.
Example of coordinates and configuration values
## Example of GPS coordinates
home_location = (34.0522, -118.2437)
## Example of fixed configuration (min, max)
password_length_range = (8, 64)
min_len, max_len = password_length_range
print(min_len, max_len)
Tuples often appear when a function returns multiple values:
def get_min_max(values):
return min(values), max(values)
scores = [78, 92, 85, 88]
score_range = get_min_max(scores)
print(score_range) # (78, 92)
If you’re collecting examples of examples of basic data types in Python used in APIs, tuples frequently show up in library return values where the structure shouldn’t change.
Sets: examples of unique, unordered collections
Sets (set) store unique items with no guaranteed order. They shine when you care about membership and uniqueness, not position.
Example of removing duplicates
emails = [
"alex@example.com",
"jordan@example.com",
"alex@example.com", # duplicate
]
unique_emails = set(emails)
print(unique_emails)
Examples include fast membership checks
blocked_users = {"spammer123", "bot_999", "troll_account"}
username = "spammer123"
if username in blocked_users:
print("Access denied")
More real examples:
- Unique tags on a blog post
- Distinct error codes encountered during a test run
- Unique courses a student is enrolled in
When you compare examples of lists vs sets, sets win for fast in checks, while lists win when order matters.
Dictionaries: real examples of structured data
Dictionaries (dict) map keys to values. They’re the backbone of a lot of Python code, especially anything that looks like JSON.
Example of a user profile
user = {
"id": 501,
"name": "Alex Smith",
"email": "alex@example.com",
"is_active": True,
"roles": ["editor", "moderator"],
}
print(user["email"]) # access a value
user["last_login"] = "2025-02-15T10:30:00Z" # add a new key
Best examples of dictionaries in real apps
Examples include:
- JSON responses from web APIs
- Configuration settings
- Caching data in memory (
cache[key] = value)
Here’s an example of a small configuration dictionary:
config = {
"debug": True,
"database": {
"host": "localhost",
"port": 5432,
},
"allowed_origins": ["https://example.com"],
}
If you’re building apps that touch health or education data, dictionaries often represent records like patient visits, course enrollments, or survey responses. For domain background (not code), organizations like the National Institutes of Health (https://www.nih.gov) and Harvard’s online resources (https://www.harvard.edu) are common reference points when designing your data model.
Modern twist (2024–2025): type hints with basic data types
Python’s type hints have become standard practice in many teams by 2024–2025. They don’t change how the code runs, but they make your intent clearer and help tools catch bugs.
Here are examples of examples of basic data types in Python with type hints:
from typing import List, Dict, Set, Tuple
user_id: int = 501
rating: float = 4.9
name: str = "Alex"
is_active: bool = True
scores: List[int] = [88, 92, 79]
coordinates: Tuple[float, float] = (37.7749, -122.4194)
tags: Set[str] = {"python", "data"}
profile: Dict[str, str] = {
"first_name": "Alex",
"last_name": "Smith",
}
Static analyzers (like mypy) and modern IDEs use these hints to warn you when you mix types in a way that doesn’t make sense. When you’re looking for the best examples of reliable Python code in 2025, you’ll almost always see type hints paired with these basic data types.
The official Python docs have an up-to-date section on typing here: https://docs.python.org/3/library/typing.html
Pulling it together: combining basic data types in a mini example
To finish, let’s build a small, realistic snippet that uses several of these types together. This is one of the best examples of how basic data types show up in real code.
Imagine a tiny function for a subscription service that:
- Takes a list of user dictionaries
- Filters active users
- Calculates the average monthly spend
- Returns a summary dictionary
from typing import List, Dict
User = Dict[str, object]
def summarize_active_users(users: List[User]) -> Dict[str, float]:
active_users = [u for u in users if u.get("is_active") is True]
if not active_users:
return {"count": 0, "avg_monthly_spend": 0.0}
total_spend = sum(float(u.get("monthly_spend", 0.0)) for u in active_users)
avg_spend = total_spend / len(active_users)
return {
"count": len(active_users),
"avg_monthly_spend": avg_spend,
}
users_data = [
{"id": 1, "name": "Alex", "is_active": True, "monthly_spend": 29.99},
{"id": 2, "name": "Jordan", "is_active": False, "monthly_spend": 0.0},
{"id": 3, "name": "Taylor", "is_active": True, "monthly_spend": 15.50},
]
summary = summarize_active_users(users_data)
print(summary)
## Example output: {'count': 2, 'avg_monthly_spend': 22.745}
In this single snippet, examples of examples of basic data types in Python are working together:
intfor user IDs and countsfloatfor monthly spend and averagesstrfor names and keysboolforis_activelistforusers_dataandactive_usersdictfor each user and the summary
This is exactly the kind of pattern you’ll see in real-world APIs, dashboards, and data pipelines.
FAQ: examples of basic data types in Python
Q: What are common examples of basic data types in Python for beginners?
Common examples include int (integers), float (decimal numbers), str (strings/text), and bool (booleans). You’ll also quickly run into list, tuple, set, and dict as core collection types.
Q: Can you give an example of combining different data types in one structure?
Yes. A user dictionary is a classic example: {"id": 1, "name": "Alex", "is_active": True, "tags": ["python", "beginner"]}. That single object mixes an integer, strings, a boolean, and a list.
Q: Which data type should I use for money in Python?
For quick scripts, many people use float, but for anything where rounding must be controlled (like billing systems), the decimal.Decimal type is safer. It avoids some of the rounding surprises you get with binary floats.
Q: Are lists or sets better for checking if a value exists?
If you care about order or duplicates, use a list. If you care about fast membership checks and uniqueness, use a set. For example, if email in blocked_emails_set: is typically faster than checking a list.
Q: Where can I see more official examples of Python data types?
The official Python tutorial has clear examples of basic data types in Python in its introductory section: https://docs.python.org/3/tutorial/introduction.html. It’s a good companion to the real-world snippets you’ve seen here.
Related Topics
Examples of Data Analysis with Pandas: 3 Practical Examples You’ll Actually Use
Practical examples of data visualization with Matplotlib in Python
Practical examples of examples of basic data types in Python
8 examples of working with dictionaries in Python – 3 practical examples you’ll use every day
Examples of Context Managers in Python: 3 Practical Patterns You’ll Actually Use
Examples of error handling in Python: practical examples for real projects
Explore More Python Code Snippets
Discover more examples and insights in this category.
View All Python Code Snippets