Lists

3.1. Lists#

In Python, a list allows us to store a collection of items in a particular order.

Here is an example of a to do list that you might have.

  • Buy carrots

  • Wash car

  • Study for quiz

We would create this in Python with the following:

todo = ['Buy carrots', 'Wash car', 'Study for quiz']
print(todo)
  • A list is defined by square brackets []

  • Items in a list are separated by commas ,

Lists can also store numbers.

numbers = [1, 2, 3, 4]
print(numbers)

In fact, you can actually store lots of different variable types in a list.

items = [1, 'hi', 2.25]
print(items)

A list is actually another type of variable.

Question 1

Which of the following correctly creates a list of colours?

  1. colours = 'pink', 'orange', 'purple'
    
  2. colours = ['red', 'yellow', 'black']
    
  3. colours = ['green' 'blue']
    
  4. colours = ('white', 'red')
    
Solution
colours = 'pink', 'orange', 'purple'

Not a list. You’ll notice that the square brackets are missing. The program still runs, but colours will not be a list (it’ll be something called a tuple).

colours = ['red', 'yellow', 'black']

Is a list.

colours = ['green' 'blue']

Is a list, but exhibits unexpected behaviour. Notice that the commas are missing. This means that Python automatically joins the strings together so you have a list with the ‘colour’ "greenblue" rather than a list with the colours green and blue.

colours = ('white', 'red')

Not a list. You’ll notice that this used circular brackets. This means that colours will not be a list (it’ll be something called a tuple).

Question 2

What would the output of the following code be?

list1 = ['red', 'green', 'blue']
list2 = ['red', 'blue', 'green']

print(list1 == list2)
Solution

Solution is locked