Lab 04: Lists, Tuples & Sets

🎯 Objective

Master Python's three sequence/collection types: lists (mutable sequences), tuples (immutable sequences), and sets (unique unordered collections).

πŸ“š Background

Python has rich built-in collection types. Lists store ordered mutable sequences. Tuples store ordered immutable sequences (faster, safer for fixed data). Sets store unique unordered items with O(1) membership tests. Each excels in different scenarios.

⏱️ Estimated Time

30 minutes

πŸ“‹ Prerequisites

  • Lab 3: Strings

πŸ› οΈ Tools Used

  • Python 3.12

πŸ”¬ Lab Instructions

Step 1: List Basics

πŸ“Έ Verified Output:

Step 2: Modifying Lists

πŸ“Έ Verified Output:

Step 3: List Operations

πŸ“Έ Verified Output:

Step 4: Tuples (Immutable)

πŸ“Έ Verified Output:

πŸ’‘ Tuples are immutable β€” safer for data that shouldn't change (coordinates, RGB values, database records). They're also ~30% faster than lists for iteration.

Step 5: Sets

πŸ“Έ Verified Output:

Step 6: List Comprehensions

πŸ“Έ Verified Output:

Step 7: Nested Lists (Matrix)

πŸ“Έ Verified Output:

Step 8: When to Use Each

πŸ“Έ Verified Output:

βœ… Verification

Expected output:

🚨 Common Mistakes

  • (42) is just 42 β€” use (42,) for single-element tuple

  • list.sort() returns None; sorted() returns new list

  • Sets are unordered β€” don't rely on order

  • b = a makes alias; use b = a.copy() or b = list(a) to copy

πŸ“ Summary

  • List []: ordered, mutable, duplicates allowed β€” for sequences

  • Tuple (): ordered, immutable β€” for fixed records, function returns

  • Set {}: unordered, unique, O(1) membership β€” for deduplication

  • List comprehensions are concise and Pythonic

  • sorted() returns new list; .sort() modifies in place

πŸ”— Further Reading

Last updated