Collection Operations and Conversions
Unit ID: M03-U07 Estimated active time: 22-30 minutes
Use built-ins for clear whole-collection questions
module_minutes = [20, 35, 25, 40]
print(len(module_minutes))
print(sum(module_minutes))
print(min(module_minutes))
print(max(module_minutes))
These functions answer common questions without writing a loop. Module 4 will show how loops build custom processing.
Sort without changing the source
titles = ["Values", "Collections", "Basics"]
sorted_titles = sorted(titles)
print(titles)
print(sorted_titles)
sorted() returns a new list. The original remains unchanged.
The list method .sort() changes the list in place and returns None:
working_titles = titles.copy()
working_titles.sort()
Choose by whether source order must be preserved.
Convert between suitable collection types
Remove duplicate tags:
raw_tags = ["python", "data", "python"]
unique_tags = set(raw_tags)
display_tags = sorted(unique_tags)
print(display_tags)
The set removes duplicates; sorted() creates predictable display order.
Create a fixed snapshot:
module_sequence = ["Values", "Collections", "Control flow"]
sequence_snapshot = tuple(module_sequence)
This does not freeze the original list. It creates a new tuple containing the current values.
Convert dictionary views for display
course = {"code": "PY-01", "hours": 32}
field_names = list(course.keys())
field_pairs = list(course.items())
The resulting lists can be indexed or displayed. Do not convert merely to follow a habit; use the view directly when conversion adds no value.
Membership works across collections
print("python" in raw_tags)
print("python" in unique_tags)
print("code" in course)
For dictionaries, membership tests keys.
Practice
Given:
hours = [8, 32, 24]
tags = ["beginner", "python", "beginner", "data"]
Calculate the count, total, minimum, and maximum hours. Create a sorted list of unique tags without changing tags. Confirm that the original order and duplicates remain in tags.
Takeaway
Built-ins answer common collection questions clearly. Preserve source order and duplicates unless the task explicitly says to change them. Comprehensions are deferred until after ordinary loops so their hidden iteration is already understood. Next, you will model and safely transform a complete small dataset.
