Python Data Types
Introduction
In Python, data types are the classification of data items. Data types represent the kind of value that tells what operations can be performed on a particular data. Python has several built-in data types that allow you to store and manipulate different kinds of information.
Understanding data types is fundamental to programming in Python because:
- They determine what values a variable can hold
- They define what operations can be performed on the data
- They influence how memory is allocated for your data
- They affect the performance and behavior of your code
Let's explore the different data types available in Python and how to work with them.
Basic Data Types in Python
Numbers
Python supports different numerical types:
Integers
Integers are whole numbers without a decimal point.
# Integer examples
x = 10
y = -5
big_number = 1234567890
print(x) # Output: 10
print(type(x)) # Output: <class 'int'>
Floating Point Numbers
Floats are numbers with a decimal point.
# Float examples
pi = 3.14159
e = 2.71828
negative_float = -0.5
print(pi) # Output: 3.14159
print(type(pi)) # Output: <class 'float'>
Complex Numbers
Complex numbers have a real and imaginary part.
# Complex number examples
c = 3 + 4j
print(c) # Output: (3+4j)
print(type(c)) # Output: <class 'complex'>
print(c.real) # Output: 3.0
print(c.imag) # Output: 4.0
Strings
Strings are sequences of characters enclosed in quotes (single or double).
# String examples
name = "Python"
message = 'Hello, World!'
multiline = """This is a
multiline string"""
print(name) # Output: Python
print(type(name)) # Output: <class 'str'>
# String operations
print(name + " Programming") # Output: Python Programming
print(name * 3) # Output: PythonPythonPython
print(name[0]) # Output: P (first character)
print(name[1:4]) # Output: yth (slicing)
print(len(message)) # Output: 13 (length of string)
Boolean
Booleans represent truth values: either True
or False
.
# Boolean examples
is_python_fun = True
is_coding_hard = False
print(is_python_fun) # Output: True
print(type(is_python_fun)) # Output: <class 'bool'>
# Boolean operations
print(is_python_fun and is_coding_hard) # Output: False
print(is_python_fun or is_coding_hard) # Output: True
print(not is_coding_hard) # Output: True
Sequence Types
Lists
Lists are ordered, mutable collections that can contain items of different data types.
# List examples
fruits = ['apple', 'banana', 'cherry']
mixed_list = [1, 'hello', 3.14, True]
print(fruits) # Output: ['apple', 'banana', 'cherry']
print(type(fruits)) # Output: <class 'list'>
# List operations
fruits.append('orange') # Add an item
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove('banana') # Remove an item
print(fruits) # Output: ['apple', 'cherry', 'orange']
print(fruits[0]) # Output: apple (first item)
print(fruits[-1]) # Output: orange (last item)
# List slicing
print(fruits[0:2]) # Output: ['apple', 'cherry']
# List comprehension
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Tuples
Tuples are ordered, immutable collections that can contain items of different data types.
# Tuple examples
coordinates = (10, 20)
person = ('John', 30, 'New York')
print(coordinates) # Output: (10, 20)
print(type(coordinates)) # Output: <class 'tuple'>
# Tuple operations
print(coordinates[0]) # Output: 10
print(person[1:]) # Output: (30, 'New York')
# Tuple unpacking
x, y = coordinates
print(x, y) # Output: 10 20
# Tuples are immutable - this will cause an error
# coordinates[0] = 15 # TypeError: 'tuple' object does not support item assignment
Mapping Type
Dictionaries
Dictionaries are unordered collections of key-value pairs.
# Dictionary examples
student = {
'name': 'John',
'age': 20,
'courses': ['Math', 'Science', 'History']
}
print(student) # Output: {'name': 'John', 'age': 20, 'courses': ['Math', 'Science', 'History']}
print(type(student)) # Output: <class 'dict'>
# Dictionary operations
print(student['name']) # Output: John
student['age'] = 21 # Modify value
print(student) # Output: {'name': 'John', 'age': 21, 'courses': ['Math', 'Science', 'History']}
student['email'] = '[email protected]' # Add new key-value pair
print(student) # Output includes the new email
# Get method with default value
print(student.get('phone', 'Not Available')) # Output: Not Available
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Set Types
Sets
Sets are unordered collections of unique elements.
# Set examples
fruits_set = {'apple', 'banana', 'cherry', 'apple'} # Duplicate will be removed
print(fruits_set) # Output: {'apple', 'banana', 'cherry'}
print(type(fruits_set)) # Output: <class 'set'>
# Set operations
fruits_set.add('orange')
print(fruits_set) # Output: {'apple', 'banana', 'cherry', 'orange'}
fruits_set.remove('banana')
print(fruits_set) # Output: {'apple', 'cherry', 'orange'}
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(set1.intersection(set2)) # Output: {4, 5}
print(set1.difference(set2)) # Output: {1, 2, 3}
Frozen Sets
Frozen sets are immutable versions of sets.
# Frozen set example
frozen = frozenset([1, 2, 3, 4])
print(frozen) # Output: frozenset({1, 2, 3, 4})
print(type(frozen)) # Output: <class 'frozenset'>
# Frozen sets are immutable - this will cause an error
# frozen.add(5) # AttributeError: 'frozenset' object has no attribute 'add'
None Type
Python has a special data type called None
which represents the absence of a value.
# None example
result = None
print(result) # Output: None
print(type(result)) # Output: <class 'NoneType'>
# Common use case
def function_without_return():
pass # Function does nothing
value = function_without_return()
print(value) # Output: None
Type Conversion
Python allows you to convert between different data types using built-in functions.
# Type conversion examples
# Converting to int
x = int(3.14)
print(x) # Output: 3
y = int("10")
print(y) # Output: 10
# Converting to float
a = float(5)
print(a) # Output: 5.0
b = float("3.14")
print(b) # Output: 3.14
# Converting to string
c = str(10)
print(c) # Output: "10"
d = str(3.14)
print(d) # Output: "3.14"
# Converting to list, tuple, set
string = "hello"
print(list(string)) # Output: ['h', 'e', 'l', 'l', 'o']
print(tuple(string)) # Output: ('h', 'e', 'l', 'l', 'o')
print(set(string)) # Output: {'h', 'e', 'l', 'o'} (note: no duplicates)
Practical Examples
Example 1: Student Management System
# A simple student management system
students = [
{
'id': 1,
'name': 'John Doe',
'age': 20,
'grades': [85, 90, 78, 88]
},
{
'id': 2,
'name': 'Jane Smith',
'age': 19,
'grades': [92, 95, 88, 91]
}
]
# Calculate average grade for each student
for student in students:
avg_grade = sum(student['grades']) / len(student['grades'])
student['average_grade'] = round(avg_grade, 2)
print(f"Student: {student['name']}, Average Grade: {student['average_grade']}")
# Output:
# Student: John Doe, Average Grade: 85.25
# Student: Jane Smith, Average Grade: 91.5
Example 2: Data Analysis with Different Data Types
# A simple data analysis example
# Product sales data
product_sales = {
'apple': [50, 65, 75, 85, 90],
'banana': [30, 40, 50, 60, 70],
'orange': [25, 35, 45, 55, 65]
}
# Calculate total and average sales for each product
product_stats = {}
for product, sales in product_sales.items():
total_sales = sum(sales)
avg_sales = total_sales / len(sales)
product_stats[product] = {
'total_sales': total_sales,
'average_sales': round(avg_sales, 2),
'best_day': max(sales),
'worst_day': min(sales)
}
# Print the stats
for product, stats in product_stats.items():
print(f"\nProduct: {product}")
print(f" Total Sales: {stats['total_sales']} units")
print(f" Average Daily Sales: {stats['average_sales']} units")
print(f" Best Day: {stats['best_day']} units")
print(f" Worst Day: {stats['worst_day']} units")
# Output:
# Product: apple
# Total Sales: 365 units
# Average Daily Sales: 73.0 units
# Best Day: 90 units
# Worst Day: 50 units
# ...etc
Checking Data Types
Python provides built-in functions to check data types.
# Using type() function
print(type(10)) # Output: <class 'int'>
print(type("hello")) # Output: <class 'str'>
print(type([1, 2, 3])) # Output: <class 'list'>
# Using isinstance() function
print(isinstance(10, int)) # Output: True
print(isinstance("hello", str)) # Output: True
print(isinstance([1, 2, 3], dict)) # Output: False
Summary
Python data types are the foundation of how we organize and manipulate data in our programs:
- Basic Types: Integers, Floats, Strings, Booleans
- Sequence Types: Lists, Tuples
- Mapping Type: Dictionaries
- Set Types: Sets, Frozen Sets
- None Type: Represents absence of value
Each data type has its own set of operations and methods. Understanding when to use each data type is crucial for effective Python programming.
- Use lists when you need an ordered, mutable collection
- Use tuples when you need an ordered, immutable collection
- Use dictionaries when you need to associate keys with values
- Use sets when you need a collection of unique elements
By mastering Python's data types, you'll be able to write more efficient and effective code.
Exercises
- Create a list of 5 different data types and use the
type()
function to confirm their types. - Write a program that converts a temperature from Celsius to Fahrenheit using proper numeric data types.
- Create a dictionary representing a book with attributes like title, author, year, and genres (as a list).
- Write a function that takes a list of numbers and returns a tuple containing the sum, minimum, and maximum values.
- Create a program that uses sets to find common elements between two lists.
Additional Resources
- Python Documentation on Data Types
- Python Data Structures Tutorial
- Real Python: Python Data Types
- W3Schools Python Data Types
Remember that mastering Python data types is a fundamental step toward becoming proficient in the language. Practice using different data types in your projects to gain a deeper understanding of when and how to use each one.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)