Lesson 13: List Methods That Matter
Learn essential Python list operations: sorting, reversing, counting items, finding indexes, checking membership, using min/max/sum, and combining lists.
Introduction
You know how to create lists, access items, and modify them. That's the foundation.
But Python provides built-in methods that handle common operations architects do constantly — sorting sheet numbers, finding the largest room area, counting how many of a certain type exist, checking if an item is in your list.
These methods save you from writing your own logic for tasks that come up repeatedly. They're fast, reliable, and used in virtually every script you'll write.
This lesson covers the list methods you'll actually use in real workflows.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Sorting lists with .sort() and sorted()
- Reversing lists with .reverse()
- Counting occurrences with .count()
- Finding items with .index()
- Checking membership with in and not in
- Finding min, max, and sum for numeric lists
- Combining lists with +
Sorting Lists
.sort() — Sort in Place
The .sort() method sorts a list in place (modifies the original list).
sheets = ["A-201", "A-101", "A-102"]
sheets.sort()
print(sheets)
# Output: ["A-101", "A-102", "A-201"]
By default, it sorts in ascending order (smallest to largest, A to Z).
For numbers:
areas = [450.5, 380.2, 520.8, 410.3]
areas.sort()
print(areas)
# Output: [380.2, 410.3, 450.5, 520.8]
Reverse order:
areas.sort(reverse=True)
print(areas)
# Output: [520.8, 450.5, 410.3, 380.2]
sorted() — Return a New Sorted List
If you want to keep the original list unchanged, use sorted() instead.
sheets = ["A-201", "A-101", "A-102"]
sorted_sheets = sorted(sheets)
print(sheets) # Output: ["A-201", "A-101", "A-102"] (unchanged)
print(sorted_sheets) # Output: ["A-101", "A-102", "A-201"]
The difference:
.sort()modifies the list, returnsNonesorted()returns a new sorted list, leaves original unchanged
For most architectural workflows, .sort() is fine. You're usually okay modifying the original list.
Architectural Example: Organizing Sheet Numbers
sheets = ["A-201", "S-101", "A-102", "A-101", "S-102"]
sheets.sort()
print(sheets)
# Output: ["A-101", "A-102", "A-201", "S-101", "S-102"]
Sheet numbers sort alphabetically, which groups them by discipline and orders them numerically within each discipline.
Reversing Lists
.reverse() — Reverse in Place
The .reverse() method reverses the order of items in a list.
floors = ["Basement", "Ground", "First", "Second"]
floors.reverse()
print(floors)
# Output: ["Second", "First", "Ground", "Basement"]
This modifies the original list.
Architectural Example: Top-Down Floor List
floors = ["Ground", "First", "Second", "Third"]
# Reverse to show from top down
floors.reverse()
print(floors)
# Output: ["Third", "Second", "First", "Ground"]
You can also reverse while sorting:
areas = [450.5, 380.2, 520.8, 410.3]
areas.sort(reverse=True)
print(areas)
# Output: [520.8, 450.5, 410.3, 380.2]
Counting Occurrences
.count() — Count How Many Times a Value Appears
Use .count() to find how many times a specific value appears in a list.
room_types = ["Office", "Meeting", "Office", "Office", "Storage"]
office_count = room_types.count("Office")
print(office_count)
# Output: 3
Architectural Example: Counting Room Types
room_types = ["Office", "Meeting", "Office", "Break Room", "Office", "Meeting"]
offices = room_types.count("Office")
meetings = room_types.count("Meeting")
print(f"Offices: {offices}")
# Output: Offices: 3
print(f"Meeting rooms: {meetings}")
# Output: Meeting rooms: 2
This is useful for quick counts without writing loops (though in Module 05, you'll learn more flexible ways to filter and count).
Finding Items
.index() — Find the Position of a Value
Use .index() to find the first position (index) where a value appears.
sheets = ["A-101", "A-102", "A-201", "A-202"]
position = sheets.index("A-201")
print(position)
# Output: 2
If the value doesn't exist, you get an error:
sheets.index("A-999")
# Error: ValueError: 'A-999' is not in list
You can check first using in:
if "A-201" in sheets:
position = sheets.index("A-201")
print(f"Found at index {position}")
Honestly, you won't use .index() as often as other methods. It's more common to just check if something exists (using in) rather than caring about its exact position.
Checking Membership
in and not in — Check if a Value Exists
The in operator checks if a value exists in a list. It returns True or False.
sheets = ["A-101", "A-102", "A-201"]
# Check if exists
if "A-101" in sheets:
print("Sheet found")
# Output: Sheet found
# Check if doesn't exist
if "S-101" not in sheets:
print("Structural sheet not in list")
# Output: Structural sheet not in list
This is one of the most useful operations. You'll use it constantly.
Architectural Example: Validating Required Sheets
required_sheets = ["A-101", "A-201", "S-101"]
submitted_sheets = ["A-101", "A-102", "A-201"]
# Check if all required sheets are submitted
for sheet in required_sheets:
if sheet in submitted_sheets:
print(f"{sheet}: ✓")
else:
print(f"{sheet}: Missing")
# Output:
# A-101: ✓
# A-201: ✓
# S-101: Missing
(This uses a loop, which you'll learn properly in Module 05. For now, just see how in works.)
Finding Min, Max, and Sum
For lists containing numbers, Python provides built-in functions.
min() — Find Smallest Value
areas = [450.5, 380.2, 520.8, 410.3]
smallest = min(areas)
print(smallest)
# Output: 380.2
max() — Find Largest Value
largest = max(areas)
print(largest)
# Output: 520.8
sum() — Add All Values
total = sum(areas)
print(total)
# Output: 1761.8
Architectural Example: Room Area Analysis
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
smallest_room = min(room_areas)
largest_room = max(room_areas)
total_area = sum(room_areas)
average_area = total_area / len(room_areas)
print(f"Smallest room: {smallest_room}m²")
print(f"Largest room: {largest_room}m²")
print(f"Total area: {total_area}m²")
print(f"Average area: {average_area:.1f}m²")
# Output:
# Smallest room: 380.2m²
# Largest room: 520.8m²
# Total area: 2157.5m²
# Average area: 431.5m²
These functions only work on lists containing numbers. If you try them on strings, you'll get unexpected results (or errors).
Combining Lists
Using + to Combine Lists
You can combine two lists using the + operator.
arch_sheets = ["A-101", "A-102"]
struct_sheets = ["S-101", "S-102"]
all_sheets = arch_sheets + struct_sheets
print(all_sheets)
# Output: ["A-101", "A-102", "S-101", "S-102"]
This creates a new list. The original lists are unchanged.
print(arch_sheets)
# Output: ["A-101", "A-102"] (unchanged)
If you want to add to an existing list (instead of creating a new one), use .extend() from the previous lesson:
arch_sheets.extend(struct_sheets)
print(arch_sheets)
# Output: ["A-101", "A-102", "S-101", "S-102"]
Real Architectural Workflows
Sorting and Analyzing Room Areas
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7, 478.2]
# Sort to see distribution
room_areas.sort()
print("Sorted areas:", room_areas)
# Output: Sorted areas: [380.2, 395.7, 410.3, 450.5, 478.2, 520.8]
# Find range
smallest = min(room_areas)
largest = max(room_areas)
print(f"Range: {smallest}m² to {largest}m²")
# Output: Range: 380.2m² to 520.8m²
# Calculate total
total = sum(room_areas)
print(f"Total area: {total}m²")
# Output: Total area: 2635.7m²
Organizing Mixed Sheet List
sheets = ["A-201", "S-101", "A-102", "M-101", "A-101", "S-102"]
# Sort alphabetically
sheets.sort()
print(sheets)
# Output: ["A-101", "A-102", "A-201", "M-101", "S-101", "S-102"]
# Count by discipline
arch_count = sum(1 for s in sheets if s.startswith("A"))
struct_count = sum(1 for s in sheets if s.startswith("S"))
mep_count = sum(1 for s in sheets if s.startswith("M"))
print(f"Architectural: {arch_count}")
print(f"Structural: {struct_count}")
print(f"MEP: {mep_count}")
# Output:
# Architectural: 3
# Structural: 2
# MEP: 1
(The counting uses list comprehensions, which we'll cover in the optional Lesson 04. For now, just see the pattern.)
Checking Required vs Submitted Sheets
required = ["A-101", "A-102", "A-201", "S-101"]
submitted = ["A-101", "A-102", "A-201"]
# Check each required sheet
missing = []
for sheet in required:
if sheet not in submitted:
missing.append(sheet)
if missing:
print("Missing sheets:", missing)
else:
print("All required sheets submitted")
# Output: Missing sheets: ['S-101']
Common Mistakes
Trying to sort mixed types
mixed = ["A-101", 101, "A-102"]
mixed.sort()
# Error: TypeError: '<' not supported between instances of 'int' and 'str'
Lists with mixed types (strings and numbers) can't be sorted. Keep your lists homogeneous.
Expecting .sort() to return the sorted list
sheets = ["A-201", "A-101", "A-102"]
sorted_sheets = sheets.sort()
print(sorted_sheets)
# Output: None
.sort() modifies the list in place and returns None. If you need the sorted result, use sorted():
sorted_sheets = sorted(sheets)
Or just use the modified original:
sheets.sort()
print(sheets)
# Output: ["A-101", "A-102", "A-201"]
Using min/max/sum on non-numeric lists
sheets = ["A-101", "A-102", "A-201"]
total = sum(sheets)
# Error: TypeError: unsupported operand type(s) for +: 'int' and 'str'
min(), max(), and sum() only work on numbers (or things that can be added/compared numerically).
For strings, min() and max() return alphabetically first/last:
sheets = ["A-201", "A-101", "A-102"]
print(min(sheets)) # Output: A-101
print(max(sheets)) # Output: A-201
This can be useful, but be aware of what it's actually doing.
Assignment
- Create a new file called
list_methods.py - Create this list:
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7] - Sort the list and print it
- Find and print:
- Smallest area
- Largest area
- Total area
- Average area (total / count)
- Create this list:
sheets = ["A-201", "S-101", "A-102", "A-101", "S-102", "A-201"] - Sort the list and print it
- Count how many times "A-201" appears
- Check if "M-101" exists in the list
- Create two lists:
floor_1_rooms = ["Office 1", "Office 2", "Conference"]floor_2_rooms = ["Office 3", "Break Room"]
- Combine them into
all_roomsusing+ - Print the total number of rooms
- Real scenario:
- You have room types:
["Office", "Meeting", "Office", "Office", "Storage", "Meeting"] - Count offices and meeting rooms
- Check if "Break Room" exists
- Sort the list alphabetically
- Print results
- You have room types:
- Experiment:
- Try to sort a list with both strings and numbers (see the error)
- Try
sorted_list = my_list.sort()and printsorted_list(see that it's None)
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- What does .sort() do to a list?
- What's the difference between .sort() and sorted()?
- What does .reverse() do?
- What does .count() return?
- How do you check if a value exists in a list?
- What does min() return for a list of numbers?
- How do you combine two lists into a new list?
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's sorting documentation covers advanced sorting techniques
- Built-in functions documentation lists all functions like min, max, sum with examples