CodeBlanks Logo Icon CodeBlanks

Summary - Lists

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

main.py
# List operations

Sample solution

main.py
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

main.py
# in and append

Sample solution

main.py
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

Question
numbers = [10, 20, 30, 40]
print(numbers[1:____])
Answer
numbers = [10, 20, 30, 40]
print(numbers[1:3])

Explanation: numbers[1:3] gives 20 and 30.

All lessons in Beginner