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:

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.

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]!

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

Q#2

Next Section - Lesson 05-02: Looping over Lists