List Operations

3.3. List Operations#

We can add items to the end of our list by appending them. To do this we use the .append() method.

Here is the syntax used for appending:

list.append(item)

Here is an example where ‘bee’ is added to the end of the list.

animals = ['lion', 'caterpillar', 'elephant']
animals.append('bee')
print(animals)
['lion', 'caterpillar', 'elephant', 'bee']

Conveniently, we can perform operations on lists. Here are a few examples:

  • len(list): Find the number of items in a list

    a = [-3, 4, 6, 1]
    print(len(a))
    
    4
    
  • min(list), max(list): Find the minimum/maximum value in a list of numbers

    a = [-3, 4, 6, 1]
    print(min(a))
    print(max(a))
    
    -3
    6
    
  • sum(list): Calculate the sum of all the values in a list of numbers

    a = [-3, 4, 6, 1]
    print(sum(a))
    
    8
    

print(information_you_want_to_display).

Question 1

What do you think the output of the following code will be?

fruits = ['apples', 'bananas', 'pears']
fruits.append('oranges')
fruits.append('watermelons')
print(fruits)
  1. ['apples', 'bananas', 'pears']
    
  2. ['apples', 'bananas', 'pears', 'watermelons']
    
  3. ['apples', 'bananas', 'pears', 'oranges', 'watermelons']
    
  4. ['apples', 'bananas', 'pears', 'watermelons', 'oranges']
    
Solution

['apples', 'bananas', 'pears']

['apples', 'bananas', 'pears', 'watermelons']

['apples', 'bananas', 'pears', 'oranges', 'watermelons']

['apples', 'bananas', 'pears', 'watermelons', 'oranges']

In this example append is used twice. Each time it’s used a new element is added to the list. First 'oranges' is added and then 'watermelons' is added.

Question 2

What do you think the output of the following code will be?

fruits = ['apples', 'bananas', 'pears']
print(len(fruits))
Solution

Solution is locked

Question 3

What do you think the output of the following code will be?

numbers = [7, 2, -1, 3, 9]
print(min(numbers))
Solution

Solution is locked

Question 4

What do you think the output of the following code will be?

numbers = [7, 2, -1, 3, 9]
print(sum(numbers))
Solution

Solution is locked

Code challenge: Another Thing To do

You have been provided with a to-do list.

todo = ['Buy carrots', 'Wash car', 'Study for quiz']

Write a program that allows the user to add an item to the to-do list. Then print the newly modified list.

Here are some examples of how your code should run.

Example 1

What else do you need to do? Cook dinner
['Buy carrots', 'Wash car', 'Study for quiz', 'Cook dinner']

Example 2

What else do you need to do? Empty bins
['Buy carrots', 'Wash car', 'Study for quiz', 'Empty bins']
Solution

Solution is locked