Python Programming: Lists


Lesson Objectives

After this lesson, you will be able to…

  • Create lists in Python.
  • Print out specific elements in a list.
  • Perform common list operations.

What is a List?

Variables hold one item.

Lists hold multiple items - and lists can hold anything.


Accessing Elements

List Index means the location of something (an element) in the list.

List indexes start counting at 0!

List “Brandi” “Zoe” “Steve” “Aleksander” “Dasha”
Index 0 1 2 3 4

We Do: Lists

  1. Create a list with the names "Holly", "Juan", and "Ming".
  2. Print the third name.
  3. Create a list with the numbers 2,4, 6, and 8.
  4. Print the first number.

List Operations - Length

len():

  • A built in list operation.
  • How long is the list?

Adding Elements: Append

.append():

  • A built in list operation.
  • Adds to the end of the list.
  • Takes any element.

Adding Elements: Insert

.insert():

  • A built in list operation.
  • Adds to any point in the list
  • Takes any element and an index.

Removing elements - Pop

.pop():

  • A built in list operation.
  • Removes an item from the end of the list.

Removing elements - Pop(index)

.pop(index):

  • A built in list operation.
  • Removes an item from the list.
  • Can take an index.

Partner Exercise: Pop, Insert, and Append

Partner up! Choose one person to be the driver and one to be the navigator, and see if you can do the prompts:


Pop, Insert, Append Solution

1. Declare a list with the names of your classmates

my_class = [“Brandi”, “Zoe”, “Steve”, “Aleksander”, “Dasha”, “Sonyl”]

4. Delete the first name on the list

deleted_classmate = my_class.pop(0)

5. Re-add the name you deleted to the end of the list

my_class.append(deleted_classmate)

print(my_class)


!! List Mutation: Warning !!

This won’t work as expected - don’t do this!

This will work - do this!


Quick Review: Basic List Operations


Numerical List Operations - Sum

Some actions can only be performed on lists with numbers.

sum():

  • A built in list operation.
  • Adds the list together.
  • Only works on lists with numbers!

List Operations - Max/Min

max() or min():

  • Built in list operations.
  • Finds highest, or lowest, in the list.
  • Only works on lists with numbers!

You Do: Lists

On your local computer, create a .py file named list_practice.py. In it:

  1. Save a list with the numbers 2, 4, 6, and 8 into a variable called numbers.
  2. Print the max of numbers.
  3. Pop the last element in numbers off; re-insert it at index 2.
  4. Pop the second number in numbers off.
  5. Append 3 to numbers.
  6. Print out the average number (divide the sum of numbers by the length).
  7. Print numbers.

Summary and Q&A

We accomplished quite a bit!


Summary and Q&A

And for numerical lists only…


Additional Resources