Quiz 2

Lists — Basics & Operations

1136 words
6 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Lists — Basics & Operations > **Why read this?** You've stored single values (a number, a string). But what about a shopping list, student names, or daily temperatures?

Lists — Basics & Operations

Why read this? You've stored single values (a number, a string). But what about a shopping list, student names, or daily temperatures? Lists are Python's way of storing collections of related items in a single variable.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Create lists with [] and the list() constructor
  2. Access and modify elements using indexing
  3. Slice lists to extract subsequences
  4. Use list methods: append, insert, remove, pop, sort, reverse
  5. Understand list mutability vs. string immutability

📋 Prerequisites


📖 Core Content

14.1 What Problem Do Lists Solve?

Intuition: A variable holds one value. A list holds MANY values. Instead of student1 = "Alice"; student2 = "Bob"; student3 = "Charlie", you write students = ["Alice", "Bob", "Charlie"] — one name, many items.

14.2 Creating Lists

python
# runnable
empty = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [1, 2], [3, 4], [5, 6](/courses/bscs1002/notes/1%2C%202%5D%2C%20%5B3%2C%204%5D%2C%20%5B5%2C%206)  # list of lists
print(empty)
print(numbers)
print(mixed)
print(nested)
# Using list() constructor
chars = list("Python")
print(chars)  # ['P', 'y', 't', 'h', 'o', 'n']
# Range to list
nums = list(range(5))
print(nums)  # [0, 1, 2, 3, 4]

14.3 Indexing and Slicing (Same as Strings!)

python
# runnable
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Indexing
print(fruits[0])    # apple (first)
print(fruits[-1])   # elderberry (last)
print(fruits[2])    # cherry
# Slicing [start:stop:step]
print(fruits[1:4])      # ['banana', 'cherry', 'date']
print(fruits[:3])       # ['apple', 'banana', 'cherry']
print(fruits[::2])      # ['apple', 'cherry', 'elderberry']
print(fruits[::-1])     # reversed list

14.4 Lists Are Mutable (Unlike Strings!)

python
# runnable
fruits = ["apple", "banana", "cherry"]
print("Original:", fruits)
# Modify an element
fruits[1] = "blueberry"
print("After change:", fruits)  # ['apple', 'blueberry', 'cherry']
# Add elements
fruits.append("date")
print("After append:", fruits)
# Insert at position
fruits.insert(1, "apricot")
print("After insert:", fruits)
# Remove by value
fruits.remove("apple")
print("After remove:", fruits)
# Remove by index (pop)
last = fruits.pop()
print(f"Popped: {last}, Remaining: {fruits}")
first = fruits.pop(0)
print(f"Popped first: {first}, Remaining: {fruits}")
# Delete by index
del fruits[0]
print("After del:", fruits)

14.5 List Methods Reference

MethodDescriptionExampleResult
append(x)Add x to end[1].append(2)[1, 2]
insert(i, x)Insert x at i[1,3].insert(1,2)[1, 2, 3]
remove(x)Remove first x[1,2,3].remove(2)[1, 3]
pop(i)Remove & return at i[1,2,3].pop(1)2, list→[1,3]
pop()Remove & return last[1,2,3].pop()3
index(x)Find index of x[1,2,3].index(2)1
count(x)Count x in list[1,2,2,3].count(2)2
sort()Sort list in-place[3,1,2].sort()[1, 2, 3]
reverse()Reverse list in-place[1,2,3].reverse()[3, 2, 1]
copy()Shallow copya.copy()New list

14.6 Sorting Lists

python
# runnable
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# In-place sort (modifies original)
numbers.sort()
print("In-place sort:", numbers)
# sorted() returns new list (original unchanged)
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print("Original:", original)
print("Sorted:", sorted_list)
# Descending
numbers.sort(reverse=True)
print("Descending:", numbers)
# By key (e.g., length of string)
words = ["python", "java", "c", "javascript", "go"]
words.sort(key=len)
print("By length:", words)

14.7 Iterating Over Lists

python
# runnable
fruits = ["apple", "banana", "cherry"]
# Direct iteration
for fruit in fruits:
    print(f"I like {fruit}")
# With index
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")
# enumerate() — best of both
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

14.8 Checking Membership

python
# runnable
fruits = ["apple", "banana", "cherry", "date"]
print("banana" in fruits)    # True
print("grape" in fruits)     # False
print("grape" not in fruits) # True

14.9 List Operations

python
# runnable
# Concatenation
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print("Concatenated:", c)
# Repetition
zeros = [0] * 5
print("Repeated:", zeros)
# Length
print("Length:", len(fruits))
# Min, Max, Sum (for numeric lists)
nums = [10, 20, 30, 40, 50]
print("Min:", min(nums))
print("Max:", max(nums))
print("Sum:", sum(nums))
print("Average:", sum(nums) / len(nums))

14.10 Worked Example 1: List Statistics

python
# runnable
numbers = [15, 22, 8, 31, 14, 27, 9, 3]
total = sum(numbers)
avg = total / len(numbers)
max_val = max(numbers)
min_val = min(numbers)
print(f"Numbers: {numbers}")
print(f"Sum: {total}")
print(f"Average: {avg:.2f}")
print(f"Max: {max_val}")
print(f"Min: {min_val}")
# Above average
above = [n for n in numbers if n > avg]
print(f"Above average: {above}")

14.11 Worked Example 2: Remove Duplicates

python
# runnable
items = ["apple", "banana", "apple", "cherry", "banana", "date"]
unique = []
for item in items:
    if item not in unique:
        unique.append(item)
print(f"Original: {items}")
print(f"Unique: {unique}")

14.12 Worked Example 3: Matrix (2D List)

python
# runnable
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
# Access element
print(f"Element [1][2]: {matrix[1][2]}")  # 6
# Print all elements
for row in matrix:
    for val in row:
        print(val, end=" ")
    print()

14.13 Worked Example 4: List as Stack

python
# runnable
stack = []
# Push
stack.append("Page 1")
stack.append("Page 2")
stack.append("Page 3")
print("Stack:", stack)
# Pop
print("Pop:", stack.pop())
print("Stack:", stack)
print("Pop:", stack.pop())
print("Stack:", stack)

📐 Key Concepts Reference

FeatureStringsLists
Mutable?NoYes
Indexings[0]lst[0]
Slicings[1:3]lst[1:3]
Method modifies?Returns new stringOften modifies in-place
Element typesOnly charactersAny types, mixed
len()YesYes
in operatorSubstring checkMembership check

⚠️ Common Pitfalls

Pitfall 1: Modifying List While Iterating

The mistake: Removing items from a list while iterating over it causes skipped elements. Fix: Iterate over a copy: for item in lst[:]:

Pitfall 2: sort() vs sorted() Confusion

The mistake: lst = lst.sort()sort() returns None and modifies in-place, so lst becomes None. Fix: Use lst.sort() (in-place) or lst = sorted(lst) (new list).

Pitfall 3: List Aliasing (Reference vs Copy)

The mistake: b = a thinking you created a copy. Both variables point to the same list. Fix: Use b = a.copy() or b = a[:] for a shallow copy.

📝 Practice Questions

Q1: What's the output?
python
lst = [1, 2, 3, 4, 5]
print(lst[1:4])
Answer: [2, 3, 4] (indices 1, 2, 3) Q2: What's wrong with this code?
python
lst = [3, 1, 2]
lst = lst.sort()
print(lst)
Answer: lst.sort() returns None. So lst becomes None. Fix: lst.sort() then print(lst). Q3: Write code to reverse a list without using reverse() or [::-1].
Answer:
python
lst = [1, 2, 3, 4, 5]
reversed_lst = []
for i in range(len(lst)-1, -1, -1):
    reversed_lst.append(lst[i])
print(reversed_lst)
Q4-10: Additional list practice questions.
(Following the same format with code answers in details blocks.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.