Python Data Types
Python uses different data types to store various kinds of information. Understanding data types helps you choose the right type for your data and avoid errors. This tutorial covers the main data types in Python with practical examples.
Basic Data Types
Numbers
Python supports integers, floating-point numbers, and complex numbers. Integers are whole numbers without decimals, while floats have decimal points.
# Integers
age = 25
year = 2023
# Floating-point numbers
price = 19.99
pi = 3.14159
# Complex numbers (less common)
complex_num = 3 + 4j
print(f"Age: {age}, Price: ${price}")You can perform mathematical operations on numbers. Learn more about numeric types in the Python documentation.
Strings
Strings store text data. You can create them with single or double quotes.
# String creation
name = "Alice"
message = 'Hello, World!'
multiline = """This is a
multiline string"""
# String operations
full_name = name + " Johnson" # Concatenation
greeting = f"Hello, {name}!" # f-strings (Python 3.6+)
print(greeting)
print(len(message)) # LengthStrings have many useful methods. Check out the string methods documentation for more operations.
Booleans
Booleans represent True or False values, often used in conditions.
is_student = True
has_license = False
# Boolean operations
is_adult = age >= 18
can_drive = is_adult and has_license
print(f"Can drive: {can_drive}")Booleans are essential for control flow. See the boolean operations guide for details.
Sequence Types
Lists
Lists are ordered collections that can hold items of different types. They’re mutable, meaning you can change them after creation.
# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["text", 42, True, 3.14]
# Accessing items
first_fruit = fruits[0] # First item
last_fruit = fruits[-1] # Last item
# Modifying lists
fruits.append("grape") # Add to end
fruits.insert(1, "kiwi") # Insert at position
fruits.remove("banana") # Remove item
popped = fruits.pop() # Remove and return last
print(f"Fruits: {fruits}")
print(f"Length: {len(fruits)}")Lists are versatile for storing collections. Explore list operations in the official tutorial.
Tuples
Tuples are similar to lists but immutable - you can’t change them after creation. They’re often used for fixed data.
# Creating tuples
coordinates = (10, 20)
person = ("John", 30, "Engineer")
single_item = (42,) # Note the comma for single item
# Accessing items (same as lists)
x, y = coordinates # Unpacking
print(f"X: {x}, Y: {y}")
# person[0] = "Jane" # This would cause an error!Tuples are useful when you need immutable sequences. Learn about tuple usage here.
Sets
Sets store unique items without duplicates. They’re useful for membership testing and mathematical operations.
# Creating sets
fruits = {"apple", "banana", "orange", "apple"} # Duplicates removed
numbers = set([1, 2, 3, 3, 2]) # From list
# Set operations
fruits.add("grape") # Add item
fruits.remove("banana") # Remove item
has_apple = "apple" in fruits # Check membership
# Mathematical operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # Union: {1, 2, 3, 4, 5}
intersection = set1 & set2 # Intersection: {3}
print(f"Union: {union}")
print(f"Intersection: {intersection}")Sets are great for unique collections. See the set documentation for more operations.
Mapping Type
Dictionaries
Dictionaries store key-value pairs. They’re like real dictionaries where you look up definitions (values) using words (keys).
# Creating dictionaries
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
# Alternative syntax
person2 = dict(name="Bob", age=25, city="Chicago")
# Accessing values
name = person["name"] # Direct access
age = person.get("age", 0) # Safe access with default
# Modifying dictionaries
person["email"] = "alice@example.com" # Add key-value
person["age"] = 31 # Update value
del person["city"] # Remove key
print(f"Name: {name}, Age: {age}")
print(f"Keys: {person.keys()}")
print(f"Values: {person.values()}")Dictionaries are fundamental for structured data. Check the dictionary guide for advanced usage.
Special Types
None
None represents the absence of a value. It’s often used as a default or placeholder.
result = None
def find_item(items, target):
for item in items:
if item == target:
return item
return None # Not found
found = find_item([1, 2, 3], 4)
print(f"Found: {found}") # NoneNone is useful for optional returns. Learn more in the None documentation.
Type Conversion
You can convert between data types using built-in functions.
# Converting to string
age_str = str(25)
price_str = str(19.99)
# Converting to numbers
num_int = int("42")
num_float = float("3.14")
# Converting sequences
list_from_tuple = list((1, 2, 3))
tuple_from_list = tuple([4, 5, 6])
set_from_list = set([1, 2, 2, 3]) # Removes duplicates
print(f"Age string: {age_str} (type: {type(age_str)})")
print(f"Number from string: {num_int} (type: {type(num_int)})")Type conversion is essential for data manipulation. See type conversion functions for all options.
Checking Types
Use the type() function to check an object’s type, or isinstance() for more flexible checking.
data = [1, 2, 3]
print(type(data)) # <class 'list'>
print(isinstance(data, list)) # True
print(isinstance(data, (list, tuple))) # True (checks multiple types)
# Type checking in functions
def process_number(num):
if not isinstance(num, (int, float)):
raise TypeError("Must be a number")
return num * 2
result = process_number(5)
print(f"Result: {result}")Type checking helps prevent errors. Explore type checking in the documentation.
Best Practices
Choose the right type: Use lists for ordered collections, dictionaries for key-value data, sets for unique items.
Be consistent: If a function returns a list, always return a list (even empty).
Type hints: In modern Python, use type hints for clarity (covered in advanced tutorials).
Avoid type conversion in loops: Convert once outside the loop for better performance.
Common Mistakes
- Forgetting the comma in single-item tuples:
(42,)not(42) - Using mutable objects as default arguments (covered in functions tutorial)
- Confusing
==(value equality) withis(identity check)
External Resources:
Related Tutorials: