Summary - Lists
- Python course
- Beginner
- Lesson 58/116
- 5 min
Combine append, sort and slice to write a class list.
Summary - Lists
In this group you learned list declaration, index/slice, methods, in/count and sorting.
- [] declares a list.
- Indexes start at 0, slices [a:b] exclude b.
- append, insert, remove, pop methods.
- in and count for search.
- sort and sorted for ordering.
Now two tasks combine these concepts.
Practice List operations
Assign fruits = ["Banana", "Apple", "Pear"]. Call fruits.sort(). Print print(fruits). Then print print(fruits[0]).
Starter code
# List operationsSample solution
fruits = ["Banana", "Apple", "Pear"]
fruits.sort()
print(fruits)
print(fruits[0])Expected output
['Apple', 'Banana', 'Pear'] Apple
Practice in and append
Assign cart = ["Apple", "Bread"]. Write if "Milk" not in cart: cart.append("Milk"). Print print(cart).
Starter code
# in and appendSample solution
cart = ["Apple", "Bread"]
if "Milk" not in cart:
cart.append("Milk")
print(cart)Expected output
['Apple', 'Bread', 'Milk']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is wrong?
- append adds to end
- insert adds at index
- remove removes an item
- pop adds an item Correct answer
Explanation: pop removes an item, it does not add one.
2 Complete the slice
numbers = [10, 20, 30, 40]
print(numbers[1:____])
numbers = [10, 20, 30, 40]
print(numbers[1:3])
Explanation: numbers[1:3] gives 20 and 30.