Python Data Types

Python data types classify different kinds of data items and define the operations that can be performed on them. Python has several built-in data types that are categorized into different groups based on their characteristics and usage patterns. These Python data types include numeric types, sequence types, mapping types, set types, and boolean types.

The Python interpreter automatically assigns data types to variables based on the value you assign to them. This dynamic typing feature makes Python flexible and easy to use, but understanding the underlying data types is essential for writing robust applications.

Numeric Data Types in Python

Python provides three main numeric data types for handling different kinds of numerical data.

Integer (int)

The integer data type in Python represents whole numbers without decimal points. Python integers can be positive, negative, or zero, and they have unlimited precision, meaning you can work with extremely large numbers without worrying about overflow errors.

# Integer examples
positive_number = 42
negative_number = -17
zero_value = 0
large_number = 999999999999999999999999999999

Python integers support all standard arithmetic operations including addition, subtraction, multiplication, division, and modulo operations. You can also use integers in bitwise operations and mathematical functions.

Float (float)

The float data type represents numbers with decimal points. Python floats are implemented using double precision floating-point numbers, which provide approximately 15-17 decimal digits of precision.

# Float examples
decimal_number = 3.14159
scientific_notation = 2.5e-4  # 0.00025
negative_float = -45.67

Float data types are essential when you need to work with measurements, percentages, or any calculations that require decimal precision. However, be aware that floating-point arithmetic can sometimes produce unexpected results due to binary representation limitations.

Complex (complex)

The complex data type represents numbers with both real and imaginary parts. Complex numbers are useful in mathematical computations, engineering applications, and scientific calculations.

# Complex number examples
complex_number = 3 + 4j
imaginary_only = 5j
real_and_imaginary = 2.5 + 1.8j

Complex numbers support arithmetic operations, and you can access their real and imaginary parts using the .real and .imag attributes respectively.

String Data Type (str)

The string data type is one of the most commonly used Python data types. Strings represent sequences of characters and are immutable, meaning you cannot modify them after creation. Python strings can contain letters, numbers, symbols, and special characters.

# String examples
single_quotes = 'Hello, World!'
double_quotes = "Python Programming"
multiline_string = """This is a
multiline string
example"""

Python strings support numerous operations including concatenation, repetition, slicing, and formatting. You can access individual characters using indexing and extract substrings using slicing operations.

String methods like .upper(), .lower(), .strip(), .replace(), and .split() provide powerful text manipulation capabilities. The string data type also supports formatted string literals (f-strings) for dynamic content creation.

Boolean Data Type (bool)

The boolean data type represents logical values and can only have two possible values: True or False. Boolean data types are essential for conditional statements, loops, and logical operations in Python programming.

# Boolean examples
is_valid = True
is_complete = False
result = 5 > 3  # True
comparison = 10 == 5  # False

Boolean values are often the result of comparison operations and logical expressions. Python uses boolean data types in conditional statements like if, elif, and while loops to control program flow.

Sequence Data Types

Python provides several sequence data types that store collections of items in an ordered manner.

List Data Type

Lists are mutable sequences that can store multiple items of different data types. Lists are one of the most versatile Python data types and are defined using square brackets.

# List examples
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
nested_list = [[1, 2], [3, 4], [5, 6]]
empty_list = []

Lists support various operations including appending, inserting, removing, and sorting elements. You can access list elements using indexing and modify them directly since lists are mutable.

Tuple Data Type

Tuples are immutable sequences that store multiple items in an ordered collection. Once created, you cannot modify tuple elements, making them ideal for storing constant data.

# Tuple examples
coordinates = (10, 20)
rgb_color = (255, 128, 0)
single_element = (42,)  # Note the comma
empty_tuple = ()

Tuples are useful when you need to ensure data integrity and prevent accidental modifications. They’re commonly used for returning multiple values from functions and storing related data together.

Range Data Type

The range data type represents an immutable sequence of numbers. Ranges are commonly used in loops and are memory-efficient because they generate numbers on-demand rather than storing them all in memory.

# Range examples
simple_range = range(5)  # 0, 1, 2, 3, 4
start_stop = range(2, 8)  # 2, 3, 4, 5, 6, 7
with_step = range(0, 10, 2)  # 0, 2, 4, 6, 8

Range objects are particularly useful in for loops and when you need to generate sequences of numbers for mathematical operations or iterations.

Mapping Data Type - Dictionary (dict)

The dictionary data type stores key-value pairs and provides fast lookup operations. Dictionaries are mutable and unordered collections that use hash tables for efficient data retrieval.

# Dictionary examples
student_grades = {"Alice": 95, "Bob": 87, "Charlie": 92}
mixed_dict = {"name": "John", "age": 25, "is_student": True}
nested_dict = {"person": {"name": "Jane", "age": 30}}
empty_dict = {}

Dictionary keys must be immutable data types (strings, numbers, or tuples), while values can be any Python data type. Dictionaries support operations like adding, updating, and removing key-value pairs.

Set Data Types

Python provides two set data types for storing unique collections of items.

Set Data Type

Sets are mutable collections of unique elements. They’re useful for removing duplicates and performing mathematical set operations.

# Set examples
unique_numbers = {1, 2, 3, 4, 5}
mixed_set = {1, "hello", 3.14}
from_list = set([1, 2, 2, 3, 3, 4])  # {1, 2, 3, 4}
empty_set = set()

Sets support operations like union, intersection, difference, and symmetric difference, making them powerful tools for data analysis and comparison operations.

Frozen Set Data Type

Frozen sets are immutable versions of sets. Once created, you cannot add or remove elements from frozen sets.

# Frozen set examples
immutable_set = frozenset([1, 2, 3, 4])
frozen_from_set = frozenset({1, 2, 3})

Frozen sets can be used as dictionary keys or elements in other sets because they’re immutable and hashable.

Type Checking and Conversion

Python provides built-in functions to check and convert between different data types.

# Type checking examples
number = 42
print(type(number))  # <class 'int'>
print(isinstance(number, int))  # True

# Type conversion examples
string_number = "123"
converted_int = int(string_number)
converted_float = float(string_number)

Understanding type checking and conversion is essential when working with user input, file processing, and data validation in Python applications.

Complete Example: Working with Python Data Types

Here’s a comprehensive example that demonstrates various Python data types in action:

#!/usr/bin/env python3
"""
Complete Python Data Types Example
This script demonstrates all major Python data types with practical examples.
"""

# Import required modules
import math
from datetime import datetime

def demonstrate_data_types():
    """Demonstrate all Python data types with practical examples."""
    
    print("=== PYTHON DATA TYPES DEMONSTRATION ===\n")
    
    # Numeric Data Types
    print("1. NUMERIC DATA TYPES:")
    integer_age = 25
    float_price = 19.99
    complex_impedance = 3 + 4j
    
    print(f"Integer (age): {integer_age} - Type: {type(integer_age)}")
    print(f"Float (price): ${float_price} - Type: {type(float_price)}")
    print(f"Complex (impedance): {complex_impedance} - Type: {type(complex_impedance)}")
    print(f"Complex real part: {complex_impedance.real}")
    print(f"Complex imaginary part: {complex_impedance.imag}")
    print()
    
    # String Data Type
    print("2. STRING DATA TYPE:")
    user_name = "Alice Johnson"
    product_description = '''This is a high-quality
    multi-line product description
    with detailed specifications.'''
    
    print(f"User name: {user_name} - Type: {type(user_name)}")
    print(f"Name length: {len(user_name)}")
    print(f"Uppercase: {user_name.upper()}")
    print(f"Name parts: {user_name.split()}")
    print(f"Formatted: Hello, {user_name}!")
    print()
    
    # Boolean Data Type
    print("3. BOOLEAN DATA TYPE:")
    is_premium_user = True
    has_discount = False
    age_verification = integer_age >= 18
    
    print(f"Premium user: {is_premium_user} - Type: {type(is_premium_user)}")
    print(f"Has discount: {has_discount}")
    print(f"Age verification: {age_verification}")
    print(f"Logical AND: {is_premium_user and age_verification}")
    print()
    
    # List Data Type
    print("4. LIST DATA TYPE:")
    shopping_cart = ["laptop", "mouse", "keyboard", "monitor"]
    mixed_data = [1, "hello", 3.14, True, [1, 2, 3]]
    
    print(f"Shopping cart: {shopping_cart} - Type: {type(shopping_cart)}")
    print(f"First item: {shopping_cart[0]}")
    print(f"Cart length: {len(shopping_cart)}")
    
    # Modify list (mutable)
    shopping_cart.append("webcam")
    shopping_cart.remove("mouse")
    print(f"Modified cart: {shopping_cart}")
    print()
    
    # Tuple Data Type
    print("5. TUPLE DATA TYPE:")
    coordinates = (10.5, 20.3)
    rgb_color = (255, 128, 64)
    database_record = ("John", 30, "Engineer", 75000)
    
    print(f"Coordinates: {coordinates} - Type: {type(coordinates)}")
    print(f"X coordinate: {coordinates[0]}")
    print(f"Y coordinate: {coordinates[1]}")
    print(f"RGB color: {rgb_color}")
    print(f"Database record: {database_record}")
    print()
    
    # Dictionary Data Type
    print("6. DICTIONARY DATA TYPE:")
    student_info = {
        "name": "Emma Smith",
        "age": 22,
        "major": "Computer Science",
        "gpa": 3.8,
        "courses": ["Python", "Data Structures", "Algorithms"]
    }
    
    print(f"Student info: {student_info} - Type: {type(student_info)}")
    print(f"Student name: {student_info['name']}")
    print(f"Student GPA: {student_info['gpa']}")
    print(f"Dictionary keys: {list(student_info.keys())}")
    
    # Add new key-value pair
    student_info["graduation_year"] = 2025
    print(f"Updated info: {student_info}")
    print()
    
    # Set Data Type
    print("7. SET DATA TYPE:")
    unique_skills = {"Python", "Java", "JavaScript", "SQL"}
    numbers_with_duplicates = [1, 2, 2, 3, 3, 3, 4, 4, 5]
    unique_numbers = set(numbers_with_duplicates)
    
    print(f"Unique skills: {unique_skills} - Type: {type(unique_skills)}")
    print(f"Original numbers: {numbers_with_duplicates}")
    print(f"Unique numbers: {unique_numbers}")
    
    # Set operations
    additional_skills = {"Python", "C++", "Go", "Rust"}
    common_skills = unique_skills.intersection(additional_skills)
    all_skills = unique_skills.union(additional_skills)
    
    print(f"Common skills: {common_skills}")
    print(f"All skills: {all_skills}")
    print()
    
    # Range Data Type
    print("8. RANGE DATA TYPE:")
    number_range = range(1, 11)
    even_numbers = range(0, 21, 2)
    
    print(f"Number range: {number_range} - Type: {type(number_range)}")
    print(f"Range values: {list(number_range)}")
    print(f"Even numbers: {list(even_numbers)}")
    print()
    
    # Frozenset Data Type
    print("9. FROZENSET DATA TYPE:")
    immutable_skills = frozenset(["Python", "Java", "C++"])
    print(f"Immutable skills: {immutable_skills} - Type: {type(immutable_skills)}")
    print()
    
    # Type Checking and Conversion
    print("10. TYPE CHECKING AND CONVERSION:")
    user_input = "42"
    print(f"User input: '{user_input}' - Type: {type(user_input)}")
    
    # Convert string to integer
    converted_number = int(user_input)
    print(f"Converted to int: {converted_number} - Type: {type(converted_number)}")
    
    # Convert integer to float
    float_number = float(converted_number)
    print(f"Converted to float: {float_number} - Type: {type(float_number)}")
    
    # Type checking with isinstance
    print(f"Is user_input a string? {isinstance(user_input, str)}")
    print(f"Is converted_number an integer? {isinstance(converted_number, int)}")
    print()
    
    # Complex Data Structure Example
    print("11. COMPLEX DATA STRUCTURE:")
    company_data = {
        "name": "TechCorp",
        "founded": 2010,
        "employees": [
            {"name": "Alice", "department": "Engineering", "salary": 95000},
            {"name": "Bob", "department": "Marketing", "salary": 65000},
            {"name": "Charlie", "department": "Sales", "salary": 70000}
        ],
        "departments": {"Engineering", "Marketing", "Sales", "HR"},
        "quarterly_revenue": (850000, 920000, 1050000, 1200000),
        "is_profitable": True
    }
    
    print(f"Company: {company_data['name']}")
    print(f"Founded: {company_data['founded']}")
    print(f"Total employees: {len(company_data['employees'])}")
    print(f"Departments: {company_data['departments']}")
    print(f"Q4 Revenue: ${company_data['quarterly_revenue'][-1]:,}")
    print(f"Profitable: {company_data['is_profitable']}")
    
    # Calculate average salary
    total_salary = sum(emp['salary'] for emp in company_data['employees'])
    average_salary = total_salary / len(company_data['employees'])
    print(f"Average salary: ${average_salary:,.2f}")

if __name__ == "__main__":
    demonstrate_data_types()

Expected Output:

=== PYTHON DATA TYPES DEMONSTRATION ===

1. NUMERIC DATA TYPES:
Integer (age): 25 - Type: <class 'int'>
Float (price): $19.99 - Type: <class 'float'>
Complex (impedance): (3+4j) - Type: <class 'complex'>
Complex real part: 3.0
Complex imaginary part: 4.0

2. STRING DATA TYPE:
User name: Alice Johnson - Type: <class 'str'>
Name length: 13
Uppercase: ALICE JOHNSON
Name parts: ['Alice', 'Johnson']
Formatted: Hello, Alice Johnson!

3. BOOLEAN DATA TYPE:
Premium user: True - Type: <class 'bool'>
Has discount: False
Age verification: True
Logical AND: True

4. LIST DATA TYPE:
Shopping cart: ['laptop', 'mouse', 'keyboard', 'monitor'] - Type: <class 'list'>
First item: laptop
Cart length: 4
Modified cart: ['laptop', 'keyboard', 'monitor', 'webcam']

5. TUPLE DATA TYPE:
Coordinates: (10.5, 20.3) - Type: <class 'tuple'>
X coordinate: 10.5
Y coordinate: 20.3
RGB color: (255, 128, 64)
Database record: ('John', 30, 'Engineer', 75000)

6. DICTIONARY DATA TYPE:
Student info: {'name': 'Emma Smith', 'age': 22, 'major': 'Computer Science', 'gpa': 3.8, 'courses': ['Python', 'Data Structures', 'Algorithms']} - Type: <class 'dict'>
Student name: Emma Smith
Student GPA: 3.8
Dictionary keys: ['name', 'age', 'major', 'gpa', 'courses']
Updated info: {'name': 'Emma Smith', 'age': 22, 'major': 'Computer Science', 'gpa': 3.8, 'courses': ['Python', 'Data Structures', 'Algorithms'], 'graduation_year': 2025}

7. SET DATA TYPE:
Unique skills: {'JavaScript', 'SQL', 'Java', 'Python'} - Type: <class 'set'>
Original numbers: [1, 2, 2, 3, 3, 3, 4, 4, 5]
Unique numbers: {1, 2, 3, 4, 5}
Common skills: {'Python'}
All skills: {'Go', 'JavaScript', 'SQL', 'Java', 'Python', 'Rust', 'C++'}

8. RANGE DATA TYPE:
Number range: range(1, 11) - Type: <class 'range'>
Range values: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

9. FROZENSET DATA TYPE:
Immutable skills: frozenset({'Java', 'Python', 'C++'}) - Type: <class 'frozenset'>

10. TYPE CHECKING AND CONVERSION:
User input: '42' - Type: <class 'str'>
Converted to int: 42 - Type: <class 'int'>
Converted to float: 42.0 - Type: <class 'float'>
Is user_input a string? True
Is converted_number an integer? True

11. COMPLEX DATA STRUCTURE:
Company: TechCorp
Founded: 2010
Total employees: 3
Departments: {'Sales', 'Engineering', 'HR', 'Marketing'}
Q4 Revenue: $1,200,000
Profitable: True
Average salary: $76,666.67

This comprehensive example demonstrates all major Python data types in practical scenarios. The code includes proper imports, detailed comments, and real-world applications of each data type. You can save this as a Python file and run it to see how different data types work together in a complete program.