List Fundamentals
Learn lists like a teacher would: what they are, when to use them, how indexing works, and how to avoid beginner mistakes with examples and visuals.
A **list** stores multiple items in an ordered sequence. ### When to use a list Use a list when: - you care about order (first, second, third) - you need duplicates - you add/remove items often ## Creating lists ```python numbers = [10, 20, 30] names = ["Tom", "Sarah", "Mike"] mixed = ["Tom", 25, True] ``` ## Indexing (most important) Index starts from 0. ```python names = ["Tom", "Sarah", "Mike"] print(names[0]) # Tom print(names[1]) # Sarah ``` ## Negative indexing ```python print(names[-1]) # Mike (last item) ``` ## Slicing (get a part) ```python nums = [1, 2, 3, 4, 5] print(nums[1:4]) # [2, 3, 4] ``` ## Add and remove ```python fruits = ["apple", "banana"] fruits.append("orange") # add at end fruits.insert(1, "grape") # add at position print(fruits) fruits.remove("banana") # remove by value last = fruits.pop() # remove last and return it print(last) ``` ## Beginner mistakes 1) IndexError: accessing out of range ```python # names[10] # error ``` 2) Confusing copy with reference ```python a = [1, 2] b = a b.append(3) print(a) # [1,2,3] because both point to same list ``` Fix: ```python a = [1, 2] b = a.copy() b.append(3) print(a) # [1,2] ``` ## Graph: list mental model ```mermaid flowchart LR A[List] --> B[Index 0] A --> C[Index 1] A --> D[Index 2] ``` ## Remember - List is ordered and mutable - Index starts at 0 - Use copy() when you want a real copy