Tuple Built-in Methods
A tuple is an immutable sequence type—essentially a list that cannot be modified after creation. Once defined, its contents are fixed.
Purpose
Tuples store multiple values in a single container, providing memory efficiency through immutability.
Definition Syntax
Tuples are created using parentheses with elements separated by commas. Elements can be of any data type.
numbers = (1, 2, 3)
mixed = tuple((10, 'hello', [1, 2]))
# Single-element tuples require a trailing comma
single = (42,)
Common Operations
- Index-based access
- Slicing operations
- Iteration with loops
- Membership testing with
inandnot in - Length calculation via
len() - Finding element positions with
index() - Counting occurrences with
count()
Order and Mutability
Tuples maintain insertion order and are immutable—elements cannot be modified, added, or removed after creation.
Dictionary Built-in Methods
Dictionaries store data as key-value pairs, enabling fast lookup and association between unique keys and their corresponding values.
Purpose
Dictionaries model structured data where each value needs a meaningful identifier (key). Common applications include configuration settings, API responses, and database records.
Definition Syntax
Dictionaries use curly braces with key-value pairs separated by colons. Keys must be immutable (hashable), while values can be any data type.
config = {'host': 'localhost', 'port': 8080}
user_data = {('user', 'id'): 12345} # tuple as key is valid
# Numeric keys behave similarly to custom encoding
endpoints = {0: 'login', 1: 'logout'}
Essential Operations
Core Methods:
- Retrieve values by key
- Add or update key-value pairs
- Iterate over keys (default behavior)
- Check key membership
- Determine dictionary size
- Access keys, values, or items collections
data = {'name': 'Alice', 'age': 30, 'active': True}
print(data.keys()) # dict_keys(['name', 'age', 'active'])
print(data.values()) # dict_values(['Alice', 30, True])
print(data.items()) # dict_items([('name', 'Alice'), ...])
for key, val in data.items():
print(f"{key}: {val}")
Additional Methods:
get(): Retrieve value with optional default for missing keys
settings = {'theme': 'dark', 'language': 'en'}
print(settings.get('timeout', 30)) # Returns 30 since 'timeout' doesn't exist
print(settings.get('theme')) # Returns 'dark'
update(): Merge key-value pairs from another dictionarysetdefault(): Insert key only if it doesn't exist
preferences = {'color': 'blue', 'size': 'medium'}
preferences.setdefault('color', 'red') # Key exists, no change
preferences.setdefault('font', 'arial') # New key added
print(preferences) # {'color': 'blue', 'size': 'medium', 'font': 'arial'}
Order and Mutability
Dictionaries maintain insertion order (Python 3.7+) but are mutable—key-value pairs can be modified, added, or removed freely.
Set Built-in Methods
Sets store unordered collections of unique elements, supporting mathematical set operations.
Purpose
- Performing union, intersection, difference, and symmetric difference operations
- Eliminating duplicate entries from collections
- Enabling efficient membership testing
Definition Syntax
Sets use curly braces with elements separated by commas. Elements must be immutable. Creating an empty set requires the set() constructor since {} creates an empty dictionary.
unique_ids = {100, 200, 300}
empty = set()
Common Methods
Set Operations:
group_a = {1, 9, 6, 7, 10}
group_b = {3, 5, 1, 7}
print(group_a & group_b) # Intersection: {1, 7}
print(group_a | group_b) # Union: {1, 3, 5, 6, 7, 9, 10}
print(group_a - group_b) # Difference: {6, 9, 10}
print(group_a ^ group_b) # Symmetric difference: {3, 5, 6, 9, 10}
Modification Methods:
add(): Insert a single elementremove(): Delete element, raiseKeyErrorif not founddiscard(): Delete element silently if presentpop(): Remove and return an arbitrary element
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
fruits.discard('banana')
fruits.remove('apple')
removed = fruits.pop() # Returns and removes arbitrary element
Order and Mutability
Sets are unordered and mutable—elements can be added and removed, but each element must be immutable (hashable).
Shallow vs Deep Copy
Understanding copy behavior is crucial when working with nested data structures.
Regular Copy: When object B copies from object A, any mutable elements inside A will reflect changes in B because they share the same memory references.
Shallow Copy: Creates a new container but preserves references to nested mutable objects. Changes to immutable elements don't affect the copy, but modifications to nested mutable elements do.
import copy
original = [1, [2, 3], 4]
shallow = copy.copy(original)
original[0] = 99 # Shallow copy unaffected
original[1].append(5) # Shallow copy affected (nested list shares reference)
print(shallow) # [1, [2, 3, 5], 4]
Deep Copy: Recursively copies all nested objects, creating completely independent structures. No changes to the original affect the copy.
import copy
data = [1, [2, 3], 4]
deep = copy.deepcopy(data)
data[1].append(99)
print(deep) # [1, [2, 3], 4] - unchanged
Important Notes
Copy operations only apply to mutable types. Built-in methods like list.copy() perform shallow copies. Be cautious when copying containers holding nested mutable elements—use deepcopy when independent structures are required.
Data Type Summary
Storage Capacity
| Category | Types |
|---|---|
| Single value | int, float, str |
| Multiple values | list, tuple, dict, set |
Ordering
| Ordered | Unordered |
|---|---|
| str, list, tuple | dict, set |
Mutability
| Mutable | Immutable |
|---|---|
| list, dict, set | int, float, str, tuple |
Copy Behavior
Shallow and deep copy operations apply exclusively to mutable types. This distinction frequently appears in technical interviews and represents fundamental Python behavior that differs from languages lacking native mutable/immutable distinctions.