Lists and List Operations
Lists are Python's most versatile compound data structure, holding an ordered, mutable sequence of items.
What is it?
A Python `list` is written as comma-separated values inside square brackets `[item1, item2]`. Lists are mutable, meaning elements can be added, updated, or removed.
Why is it used?
Used to store collections of records, batch data, student rosters, scores, and queued tasks.
Detailed Explanation
List Operations:
• Adding items:
• `.append(x)`: Adds item to the end.
• `.insert(i, x)`: Inserts at specific index.
• `.extend(iterable)`: Appends elements from another collection.
• Removing items:
• `.pop(i)`: Removes and returns item at index (default last).
• `.remove(x)`: Removes first matching occurrence of value.
• `del list[i]`: Deletes by index.
• Ordering:
• `.sort()`: Sorts list in-place.
• `sorted(list)`: Returns a new sorted copy.
• `.reverse()`: Reverses in-place.
Syntax Structure
Syntax Blueprint
courses = ["Python", "Excel"]
courses.append("Data Analytics")
courses.sort()
Code Example
PYTHON Code
# Managing Student Admissions Queue
admissions_queue = ["Rohan Sharma", "Sneha Joshi", "Amit Deshmukh"]
# Append new walk-in student
admissions_queue.append("Pooja Patil")
print("Queue:", admissions_queue)
# Process the first student (FIFO Queue)
processed_student = admissions_queue.pop(0)
print(f"Admitted: {processed_student}")
print("Remaining Queue:", admissions_queue)
# Sorting alphabetically
admissions_queue.sort()
print("Sorted Remaining:", admissions_queue)
# Numeric list operations
scores = [85, 92, 78, 96, 88]
print(f"Highest Score: {max(scores)}")
print(f"Lowest Score: {min(scores)}")
print(f"Average Score: {sum(scores) / len(scores):.1f}")
Explanation of the Code
• `.append()` adds new entries dynamically.
• `.pop(0)` removes the first student from the front of the queue.
• Built-ins `max()`, `min()`, `sum()`, and `len()` operate on numeric lists.
Expected Output
Queue: ['Rohan Sharma', 'Sneha Joshi', 'Amit Deshmukh', 'Pooja Patil']
Admitted: Rohan Sharma
Remaining Queue: ['Sneha Joshi', 'Amit Deshmukh', 'Pooja Patil']
Sorted Remaining: ['Amit Deshmukh', 'Pooja Patil', 'Sneha Joshi']
Highest Score: 96
Lowest Score: 78
Average Score: 87.8
Real-World Application
Used across web frameworks to collect database records, manage task queues, and process CSV uploads.
Common Mistakes to Avoid
• Confusing `.sort()` (mutates original and returns `None`) with `sorted()` (returns a new list).
• Modifying a list while iterating over it (causes skipped items).
Quick Practice Challenge
Create a list of 4 fruits, sort them in reverse alphabetical order, and remove the last item.
Key Takeaways
• Lists are ordered, mutable, and enclosed in square brackets `[]`.
• Use `.append()` to add and `.pop()` to remove elements.
• Use `len()`, `sum()`, `max()`, and `min()` for fast aggregate math.