Mutable and Immutable Data Types
In Python, data types are categorized into mutable (modifiable after creation) and immutable (unmodifiable after creation) types. This classification replaces the traditional "pass-by-value" or "pass-by-reference" distinction in other languages.
Immutable Data Types
Immutable types include str, int, and float. When you modify the value of an immutable object, Python creates a new object in memory instead of altering the original one.
# Immutable type example (str)
original_str = "hello"
modified_str = original_str.upper() # Creates a new string object
print(id(original_str)) # Different memory address
print(id(modified_str)) # Different memory address
Mutable Data Types
Mutable types include list and dict. Modifying their values does not change their memory addresses, as the orignial object is altered directly.
# Mutable type example (list)
original_list = [10, 20, 30]
original_list.append(40) # Modifies the original list
print(id(original_list)) # Same memory address
Dictionary Built-in Methods
A dictionary is defined as {key: value} pairs separated by commas, where keys must be immutable (preferably strings for readability) and values can be any type.
Creating Dictionaries
# Basic creation
user_profile = {'full_name': 'alice smith', 'years': 25, 'is_student': True}
# Using dict() with keyword arguments
product_info = dict(name='laptop', price=999, brand='dell')
# From list of key-value pairs
inventory = dict([('sku_101', 50), ('sku_102', 30)])
# Using fromkeys() (initialize keys with default value)
config = dict.fromkeys(['theme', 'language', 'font_size'], 'default')
Key Operations
- Access Values: Use
get()to avoid errors if a key doesn't exist. - Update Values: Assign directly or use
update(). - Remove Items: Use
pop()(by key) orpopitem()(random key-value pair). - Iterate: Use
keys(),values(), oritems().
user_data = {'full_name': 'alice smith', 'years': 25, 'hobbies': ['reading', 'hiking']}
# Access value
print(user_data.get('full_name')) # alice smith
print(user_data.get('location', 'not specified')) # not specified
# Update dictionary
user_data.update({'years': 26, 'location': 'new york'})
# Remove and return item
removed_hobby = user_data.pop('hobbies')
print(removed_hobby) # ['reading', 'hiking']
# Iterate over items
for key, value in user_data.items():
print(f"{key}: {value}")
Tuple Built-in Methods
A tuple is an immutable sequence of values defined with parentheses ( ), used for storing fixed, unchangeable data.
Creating Tuples
# Basic creation
languages = ("python", "javascript", "java")
# Single-element tuple (requires trailing comma)
single_tuple = (10,)
print(type(single_tuple)) # <class 'tuple'>
Type Conversion
Convert any iterable (list, string, dict keys) to a tuple with tuple():
# From list
colors = tuple(['red', 'blue', 'green'])
# From string
letters = tuple('python') # ('p', 'y', 't', 'h', 'o', 'n')
Key Properties
Tuples support indexing and slicing like lists, but their elements cannot be modified. They are often used for returning multiple values from functions.
# Indexing
first_lang = languages[0] # python
# Slicing
last_two = languages[-2:]
print(last_two) # ('javascript', 'java')
Set Built-in Methods and Operations
Sets are unordered collections of unique elements, primarily used for duplicate removal and set operations (union, intersection, etc.).
Creating Sets
# Empty set
empty_set = set()
# From list
unique_numbers = set([10, 20, 20, 30]) # {10, 20, 30}
Key Use Cases
- Duplicate Removal: Convert a list to a set and back to a list.
- Set Operations: Use operators like
|(union),&(intersection),-(difference), and^(symmetric difference).
# Remove duplicates from a list
raw_list = ['apple', 'banana', 'apple', 'orange']
distinct_items = list(set(raw_list))
# Set operations
users1 = {"sarah", "mike", "david", "emily"}
users2 = {"emily", "james", "david", "lisa"}
# Union (all unique users)
all_users = users1 | users2
# Intersection (common users)
common_users = users1 & users2
# Difference (users only in users1)
only_users1 = users1 - users2