Lesson 2 of 10
A method is a function that belongs to a value. You call it with a dot: mylist.append(x).
Lists come with a set of methods for changing their contents.
Adding items
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
fruits.insert(0, "avocado")
print(fruits)
append() adds to the end — by far the most common. insert(index, item) puts an item at a
specific position and shifts everything after it along.
fruits = ["apple"]
fruits.extend(["banana", "cherry"])
print(fruits)
extend() adds every item from another list. Note the difference: append(["b", "c"]) would
add one item that happens to be a list, giving you a nested list instead.
Removing items
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
last = fruits.pop()
print(last)
print(fruits)
remove(value) deletes the first matching item by value. pop() removes and returns the
last item — useful when you want the value as you take it. pop(0) removes the first instead.
del fruits[0] and fruits.clear() also work, for deleting by index and emptying the list.
Sorting and reversing
numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)
numbers.reverse()
print(numbers)
sort() changes the list in place and returns None. That last part catches people out:
numbers = [3, 1, 2]
result = numbers.sort()
print(result)
That prints None, not a sorted list. If you want a sorted copy while leaving the original
alone, use the sorted() function instead:
numbers = [3, 1, 2]
print(sorted(numbers))
print(numbers)
Searching
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)
print(fruits.index("cherry"))
print(fruits.count("apple"))
in gives a boolean, index() gives the position, and count() gives how many times a value
appears.
Try it yourself
Start with [3, 1, 2]. Append 4, sort it, then print the list and its length.
Checkpoint
append()adds one item;extend()adds many;insert()adds at a position.remove()deletes by value;pop()deletes by position and returns the item.sort()sorts in place and returnsNone;sorted()returns a new sorted list.in,index(), andcount()search a list.
Questions about this lesson
Log in to ask a question.