Lesson 05-01: Python Lists

Learning Target: I can utilize python lists to hold various data.
Learning Target: I can reference specific elements within a list.

Data Type of Multiple Values

So far, each variable can only hold one value at a time - one integer or one float or one string. What if we wanted to hold multiple values? Like a list of prime numbers under 50? Or a list of names of students?

You can do this in python by creating a list! A list is a python datatype that can hold multiple values and has special functions, like a String. Here’s how you create a list:

numbers = [1,2,3,4,5,6]
names = ["Sally","Harry"]

Notice that it’s similar to a variable assignment statement, except the value uses square brackets ([]), and each value is separated by a comma (,).

Note that lists can hold values of different datatypes!

mixed_list = [1,2,"three",4,"5",true,None]

So once we have a list of values, how do we access them again?

Specific Elements in a List

Funnily enough, we do it exactly the same as we access strings! Just like each character in a string, each element in a list has an index and we use that index to access that value.

indexes of a list

Here’s an example:

 
1
fruits = ["apple","banana","strawberry","grape","pineapple","watermelon"]
2
print(fruits) #entire list
3
print(fruits[0]) #apple
4
print(fruits[3]) #grape
5
print(fruits[-1]) #watermelon
6
['apple', 'banana', 'strawberry', 'grape', 'pineapple', 'watermelon']
apple
grape
watermelon

(ex_0501_1)

Notice how when the list is printed, it prints the entire list, including the brackets and quotes (if it’s a string).

List Slicing

Similar to strings, you can also slice lists using the same notation.

7
 
1
numbers = [0,1,2,3,4,5,6,7,8,9]
2
print(numbers)
3
print(numbers[0:3]) #0,1,2
4
print(numbers[5:8]) #5,6,7
5
print(numbers[-5:]) #5,6,7,8,9
6
print(numbers[4:5]) #4
7
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2]
[5, 6, 7]
[5, 6, 7, 8, 9]
[4]

(ex_0501_2)

An important note - please see that in our last example, printing numbers[4:5] returned a list with the value in the 4th index. This is not the same as printing numbers[4]!

11
 
1
numbers = [0,1,2,3,4,5,6,7,8,9]
2
3
#list slice
4
print(numbers[4:5])
5
6
#list index
7
print(numbers[4])
8
9
#are they equivalent?
10
print(numbers[4] == numbers[4:5])
11
[4]
4
False

(ex_0501_3)

numbers[4:5] returns a list with the value at the 4th index. numbers[4] just returns the value at the 4th index.

We won’t be using list indexing as much in this course, but it was an interesting tidbit to share.

Checks For Understanding

Q#1

5
 
1
#complete line 3 to return the 1st element in the given list a_list
2
def getFirstElement(a_list):
3
    return
4
5

(cfu_0501_1)

Q#2

5
 
1
#complete line 3 to return the last element in the given list a_list
2
def getFirstElement(a_list):
3
    return
4
5

(cfu_0501_2)

Next Section - Lesson 05-02: Looping over Lists