Core Data Structures in Python: Lists, Tuples, and Dictionaries
Overview of Sequences
Python provides several sequence types, with strings, lists, and tuples being the most common. Lists and tuples share similar syntax but differ fundamentally in mutability: tuple are immutable once defined, while lists can be modified dynamically.
Creating Lists and Tuples
Lists are defined using square brackets [], while tuples use parentheses ().
# Creating a list
collection_list = ['data_science', 42, 'python']
print(collection_list)
# Creating a tuple
collection_tuple = ('data_science', 42, 'python')
print(collection_tuple)
Sequence Fundamentals
Indexing
Both structures support zero-based indexing. Lists allow element reassignment, but tuples do not, as they act as constants.
items = (10, 'alpha', 3.14, 'beta', -5)
print(items[0]) # First element
print(items[-1]) # Last element
Slicing
Use the [start:end:step] syntax to extract sub-sequences. Negative indices count backward from the end.
values = (0, 10, 20, 30, 40)
print(values[1:3]) # (10, 20)
print(values[-3:-1]) # (20, 30)
Concatenation and Repetition
Sequences can be combined using the + operator and repeated with the * operator. Note that you must combine like types.
# Concatenation
combined = (1, 2) + (3, 4)
# Repetition
repeated = ['x'] * 5
Note: To define a single-item tuple, you must include a trailing comma: ('singleton',).
Advanced Sequence Operations
Python provides built-in functions such as len(), max(), and min(). For max() and min() to function, all elements within the sequence must be of comparable types.
Sequence Packing and Unpacking
Packing occurs when multiple values are asssigned to a single variable, creating a tuple. Unpacking extracts sequence elements into individual variables.
# Packing
metrics = 100, 200, 300
# Unpacking with asterisk for remainder
first, *others = [1, 2, 3, 4]
print(first) # 1
print(others) # [2, 3, 4]
Manipulating Lists
Beyond basic construction, use list() to convert other iterables into lists. Modify contents using append() for single items, extend() for bulk addition, and del or remove() for deletion.
container = [1, 2, 3]
container.append(4) # Add to end
container.insert(0, 0) # Insert at index
container[1:3] = [9, 9] # Slice assignment
Dictionary Mappings
Dictionaries store data as key-value pairs. Keys must be immutable (e.g., strings, numbers, or tuples), while values can be any object. Keys must be unique.
# Dictionary creation
user_data = {'id': 101, 'status': 'active'}
# Accessing and modifying
print(user_data['id'])
user_data['status'] = 'inactive'
# Removing a key
del user_data['id']
Useful Dictionary Methods
get(key): Safely retrieves a value; returnsNoneinstead of raising aKeyErrorif the key is missing.update(other_dict): Merges another dictionary into the current one.keys(),values(), anditems(): Return views of the dictionary's contents, which can be cast to lists.