Lists
What it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβfruits = ["apple", "banana", "cherry"]
fruits.append("date") # add to the end: ['apple', 'banana', 'cherry', 'date']fruits.insert(1, "avocado") # insert at index 1fruits.remove("banana") # remove by valuefirst_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]Common mistake
Section titled βCommon mistakeβ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 inQuick practice
Section titled βQuick practiceβ-
Whatβs the difference between
list.append(x)andlist.extend(x)?Answer
appendaddsxas a single new element (even if it's a list);extendadds each item fromxindividually. -
What does
my_list[-1]return?Answer
The last element of the list β negative indices count from the end. -
Is a list comprehension faster than building a list with a
forloop and repeated.append()calls?Answer
Yes, generally β comprehensions avoid the repeated attribute lookup and function-call overhead of.append(), and CPython optimizes them internally.