Python Data Types - Complete Guide
Fundamental Data Types
# Basic types integer = 42 # int floating = 3.14 # float text = "Hello" # str boolean = True # bool nothing = None # NoneType # Collection types numbers = [1, 2, 3] # list coordinates = (4, 5) # tuple person = {"name": "Alice"} # dict unique_numbers = {1, 2, 3} # set
Numeric Types
Understanding Numeric Types
Python supports three numeric types: integers, floating-point numbers, and complex numbers. Integers can be arbitrarily large, floats follow IEEE 754 standard, and complex numbers have real and imaginary parts.
- Integers: Whole numbers without decimal points
- Floats: Numbers with decimal points or scientific notation
- Complex: Written as a + bj where a is real and b is imaginary part
# Integer operations print(10 + 3) # 13 print(10 // 3) # 3 (floor division) print(2 ** 4) # 16 (exponentiation) # Integer subtypes binary = 0b1010 # Binary literal (10) hex_num = 0x1a3 # Hexadecimal literal (419) octal = 0o777 # Octal literal (511) large_num = 1_000_000 # Underscores for readability # Float precision print(0.1 + 0.2) # 0.30000000000000004 print(round(0.1 + 0.2, 1)) # 0.3 # Floating-point precision import math print(math.isclose(0.1 + 0.2, 0.3)) # True (proper float comparison) # Type conversion print(float(5)) # 5.0 print(int(3.9)) # 3 (truncates decimal) # Complex numbers z = 3 + 4j print(z.real, z.imag) # 3.0 4.0
Strings
String Fundamentals
Strings in Python are immutable sequences of Unicode characters. They support various operations including slicing, concatenation, and formatting. Python provides multiple ways to write strings:
- Single quotes: 'hello'
- Double quotes: "world"
- Triple quotes: '''multi-line strings'''
- f-strings: f"Hello {name}" (formatted strings)
# String methods s = " Python " print(s.strip().upper()) # "PYTHON" print("hello".capitalize()) # "Hello" # String formatting name = "Alice" print(f"Hello, {name}") # Hello, Alice print("Value: {:.2f}".format(3.1415)) # Value: 3.14 # Raw strings and escape characters path = r"C:\new_folder\file.txt" # Raw string ignores escapes multiline = """Line 1 Line 2""" # Multiline string # String immutability example s = "hello" # s[0] = 'H' # TypeError s = 'H' + s[1:] # Creates new string
Collection Types Comparison
Python's built-in collection types each serve different purposes. Understanding their properties helps in choosing the right data structure:
Type | Mutable | Ordered | Use Case |
---|---|---|---|
list | Yes | Yes | Modifiable sequences |
tuple | No | Yes | Fixed data |
dict | Yes | No | Key-value pairs |
set | Yes | No | Unique elements |
Operation | List | Tuple | Set | Dict |
---|---|---|---|---|
Indexing | ✔️ | ✔️ | ❌ | By key |
Mutable | ✔️ | ❌ | ✔️ | ✔️ |
Duplicates | ✔️ | ✔️ | ❌ | Unique keys |
Type Conversion
Type Conversion Principles
Type conversion in Python can be either explicit (using constructor functions) or implicit (automatic by the interpreter). Key points:
- Explicit: int(), float(), str(), list(), etc.
- Implicit: Automatic during operations (e.g., int + float → float)
- Lossy conversions: float to int truncates decimals
- String conversion: str() returns human-readable representation
# Explicit conversion print(int("42")) # 42 print(str(3.14)) # "3.14" print(list("hello")) # ['h', 'e', 'l', 'l', 'o'] # Implicit conversion print(3 + 4.5) # 7.5 (int to float) print(True + 5) # 6 (bool to int)
Mutability in Python
# Mutable objects (can change) lst = [1, 2, 3] lst[0] = 5 # Valid # Immutable objects (cannot change) s = "hello" # s[0] = 'H' # TypeError s = "Hello" # Creates new string # Tuple with mutable element mixed = (1, [2, 3]) mixed[1].append(4) # Valid → (1, [2, 3, 4])
Memory Management
Memory Management Concepts
Python handles memory automatically through reference counting and garbage collection. Key concepts include:
- Reference Counting: Tracks number of references to each object
- Garbage Collection: Reclaims memory from unreachable objects
- Interning: Reuse of small integers and strings
- Copying: Shallow vs deep copies for compound objects
# Object identity a = [1, 2, 3] b = a print(a is b) # True (same object) # Copying objects c = a.copy() print(a is c) # False (different object) # Memory optimization for small integers x = 256 y = 256 print(x is y) # True (cached) x = 257 y = 257 print(x is y) # False (new objects)
Practice Exercises
Exercise 1: Type Identification
# For each value, write its type:
42, 3.14, True, [1, 2], {"name": "Alice"}, {1, 2}, (5,)
Exercise 2: Type Conversion
# Convert these values:
"123" → int
15 → float
[1, 2, 3] → tuple
{"a": 1, "b": 2} → list of keys
Advanced Data Types
# Bytes and Bytearray data = b'ABCDE' # Immutable bytes mutable_data = bytearray(b'12345') # Mutable mutable_data[0] = 54 # OK (ASCII '6') # Frozenset (immutable set) fs = frozenset([1, 2, 3]) # fs.add(4) # AttributeError # NoneType and identity checks result = None print(result is None) # True (preferred over ==)
Type Checking & Annotations
# Using isinstance() value = 3.14 if isinstance(value, (int, float)): print("Valid number") # Type annotations (Python 3.9+) from typing import Union def square(n: Union[int, float]) -> float: return n ** 2 # Accessing __annotations__ print(square.__annotations__) # See function type hints
Collection Type Characteristics
Python's built-in collection types each serve different purposes. Understanding their properties helps in choosing the right data structure:
Operation | List | Tuple | Set | Dict |
---|---|---|---|---|
Indexing | ✔️ | ✔️ | ❌ | By key |
Mutable | ✔️ | ❌ | ✔️ | ✔️ |
Duplicates | ✔️ | ✔️ | ❌ | Unique keys |