Lists are Python's workhorse: ordered, changeable collections that hold anything. If you learn one data structure deeply, make it this one.
Create with brackets: scores = [90, 85, 77]. Add with .append(), remove with .remove() or .pop(), sort with .sort(), measure with len(). Lists keep order and allow duplicates.
scores = [90, 85, 77] mixed = [1, "two", 3.0, True] # any types together empty = [] print(scores[0]) # 90 — first (index 0!) print(scores[-1]) # 77 — last print(len(scores)) # 3 print(85 in scores) # True
todo = ["learn python"]
todo.append("build project") # add to end
todo.insert(0, "wake up") # add at position
todo.extend(["sleep", "repeat"]) # add many
todo.remove("sleep") # remove by VALUE (first match)
last = todo.pop() # remove & return last item
first = todo.pop(0) # remove & return by INDEX
del todo[0] # delete by index, no returnnums = [3, 1, 4, 1, 5] nums.sort() # in place: [1, 1, 3, 4, 5] nums.sort(reverse=True) # [5, 4, 3, 1, 1] words = ["banana", "Apple", "cherry"] words.sort(key=str.lower) # case-insensitive sort top3 = sorted(nums)[:3] # sorted() = NEW list, original untouched
Slices work exactly like string slices — and they're also the safe way to copy.
nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] print(nums[::2]) # [10, 30, 50] — every 2nd copy = nums[:] # REAL copy alias = nums # NOT a copy — same list, two names! alias.append(60) print(nums) # [10, 20, 30, 40, 50, 60] — surprise!
squares = [n * n for n in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] evens = [n for n in range(20) if n % 2 == 0] names = ["ada", "grace", "alan"] caps = [n.title() for n in names] # ['Ada', 'Grace', 'Alan']
b = a makes two names for ONE list — changes through either name affect both. Use b = a[:] or a.copy()items[0] crashes when the list is empty — check if items: firstx = nums.sort() sets x to None! sort() works in place; use sorted(nums) for a new listappend(x) adds x as ONE item (even if x is a list); extend(xs) adds each element of xs individually.
Use new = old[:] or new = old.copy(). Plain new = old only creates a second name for the same list.
A one-line expression that builds a list: [n*n for n in range(5)]. It replaces a 3-line for-loop with clearer, faster code.
Yes — [1, "two", 3.0, True] is valid. In practice, keeping one type per list makes code easier to reason about.