Skip to content

Lists

A list is Python’s general-purpose, ordered, mutable sequence β€” [1, 2, 3]. You can add, remove, and change items after creation, access elements by index, and slice out sub-ranges. Lists are the default choice for β€œa bunch of things in order” unless you specifically need immutability (tuple) or uniqueness (set).

fruits = ["apple", "banana", "cherry"]
fruits.append("date") # add to the end: ['apple', 'banana', 'cherry', 'date']
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove by value
first_two = fruits[:2] # slicing: ['apple', 'avocado']
fruits.sort() # sort in place
numbers = [n * n for n in range(5)] # list comprehension: [0, 1, 4, 9, 16]

Using list.append() when you meant list.extend() β€” append adds its argument as a single element, even if that argument is itself a list.

combined = [1, 2, 3]
combined.append([4, 5]) # [1, 2, 3, [4, 5]] <- nested list, probably not intended
combined = [1, 2, 3]
combined.extend([4, 5]) # [1, 2, 3, 4, 5] <- correct, flattens the items in
  1. What’s the difference between list.append(x) and list.extend(x)?

    Answerappend adds x as a single new element (even if it's a list); extend adds each item from x individually.
  2. What does my_list[-1] return?

    AnswerThe last element of the list β€” negative indices count from the end.
  3. Is a list comprehension faster than building a list with a for loop and repeated .append() calls?

    AnswerYes, generally β€” comprehensions avoid the repeated attribute lookup and function-call overhead of .append(), and CPython optimizes them internally.