Working with Lists
Objective
Master list creation, indexing, slicing, mutation, and common list operations.
Tools & Technologies
listappendpopsortslicecopylist comprehension
Key Commands
lst.append(x)lst.sort(key=lambda x: x[1])lst[1:4]lst.pop()[x for x in lst if x > 0]sorted(lst, reverse=True)Architecture Overview
graph TD
LST[list = [10, 20, 30, 40, 50]]
LST --> IDX[Indexing\nlst[0]=10 lst[-1]=50]
LST --> SLC[Slicing\nlst[1:3]=[20,30]]
LST --> MUT[Mutation\nlst.append(60)\nlst.pop()]
LST --> SORT[Sorting\nsorted(lst)\nlst.sort()]
LST --> COMP[Comprehension\n[x*2 for x in lst]]
style LST fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
Step-by-Step Process
01
Indexing and Slicing
Access individual elements and ranges.
lst = [10, 20, 30, 40, 50]
lst[0] # 10 (first)
lst[-1] # 50 (last)
lst[1:3] # [20, 30] (index 1 up to but not 3)
lst[:3] # [10, 20, 30]
lst[2:] # [30, 40, 50]
lst[::2] # [10, 30, 50] (every 2nd)
lst[::-1] # [50, 40, 30, 20, 10] (reversed)
02
Mutating Lists
Add, remove, and modify elements.
lst.append(60) # add to end
lst.insert(2, 25) # insert at index 2
lst.extend([70, 80]) # add multiple
lst.pop() # remove and return last
lst.pop(0) # remove and return index 0
lst.remove(30) # remove first occurrence of 30
del lst[2] # delete index 2
lst.clear() # empty the list
03
Sorting and Searching
Sort and search lists efficiently.
nums = [3, 1, 4, 1, 5, 9, 2]
nums.sort() # in-place
nums.sort(reverse=True) # descending
sorted(nums) # returns new list
# Sort by key
people = [('Alice', 25), ('Bob', 22)]
people.sort(key=lambda x: x[1]) # by age
# Search
30 in lst # True/False
lst.index(30) # first position
lst.count(30) # occurrences
Challenges & Solutions
- list.sort() modifies in place, sorted() returns new list — common confusion
- Shallow copy with lst.copy() — nested objects still share references
Key Takeaways
- List comprehensions are typically 30-50% faster than equivalent for loops
- Use collections.deque for efficient O(1) append/pop from both ends