Using Python Lists

45 minutes
  • 4 Learning Objectives

About this Hands-on Lab

Lists are one of the fundamental data types that we use in Python for solving real problems. Being able to manipulate lists and access items is necessary for effective programming. In this hands-on lab, we’ll be working through some exercises demonstrating that we understand how to add, remove, modify, and read items from lists in Python. We’ll perform actions on a list to meet some checkpoint requirements provided to us within a Python file.

To feel comfortable completing this lab we’ll want to know how to do the following:

* Working with list literals: Watch the “Lists” video from the Certified Entry-Level Python Programmer Certification course.
* Using list functions and methods: Watch the “List Functions and Methods” video from the Certified Entry-Level Python Programmer Certification course.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create a users List and Add Initial Items

Note: The using-lists.py file exists in the /home/cloud_user/ directory. If you do not see the file, please give the lab another minute to finish provisioning. If you prefer to use your own local Python editor, you can also access the initial using-lists.py file in the lab’s GitHub repository.

Our first few tasks require us to create the users variable that we’re going to work with throughout the lab and then add some information to it. Here’s how we complete the first task:

using-lists.py (partial)

# 1) Set the users variable to be an empty list
users = []

assert users == [], f"Expected `users` to be [] but got: {repr(users)}"

Now if we run the file we should see the error for the second task:

$ python3.7 using-lists.py
Traceback (most recent call last):
  File "./using-lists.py", line 8, in <module>
    assert users == ['kevin', 'bob', 'alice'], f"Expected `users` to be ['kevin', 'bob', 'alice'] but got: {repr(users)}"
AssertionError: Expected `users` to be ['kevin', 'bob', 'alice'] but got: []

This error shows us that we need to add values to the list before we can continue. The task also specifies that we shouldn’t just reassign the users variable. Here’s an example solution to this:

using-lists.py (partial)

# 2) Add 'kevin', 'bob', and 'alice' to the users list in that order without reassigning the variable.
users.append('kevin')
users.append('bob')
users.append('alice')

assert users == ['kevin', 'bob', 'alice'], f"Expected `users` to be ['kevin', 'bob', 'alice'] but got: {repr(users)}"
Remove bob and Create rev_users List

For tasks 3 and 4 we need to remove the bob value and then create a new reversed version of the new list. Here’s an example solution for both of these tasks:

using-lists.py (partial)

# 3) Remove 'bob' from the `users` list without reassigning the variable.
del users[1]

assert users == ['kevin', 'alice'], f"Expected `users` to be ['kevin', 'alice'] but got: {repr(users)}"

# 4) Reverse the users list and assign the result to `rev_users`
rev_users = list(reversed(users))

assert rev_users == ['alice', 'kevin'], f"Expected `rev_users` to be ['alice', 'kevin'] but got: {repr(rev_users)}"

The del statement will allow us to remove an item at a specific index to complete task three. For task four, we’ll use the reversed function and then cast the result of that back to a list using the list function.

Insert melody to users and Concatenate Lists

For tasks five and six we’ll be adding more information to our users list. To add a single item at the first index we’ll use the insert method. To add three new items to the end of the list we’ll use list concatenation and reassign the users variable.

using-lists.py (partial)

# 5) Add the user 'melody' to users where 'bob' used to be.
users.insert(1, 'melody')

assert users == ['kevin', 'melody', 'alice'], f"Expected `users` to be ['kevin', 'melody', 'alice'] but got: {repr(users)}"

# 6) Add the users 'andy', 'wanda', and 'jim' to the users list using a single command
users += ['andy', 'wanda', 'jim']

assert users == ['kevin', 'melody', 'alice', 'andy', 'wanda', 'jim'], f"Expected `users` to be ['kevin', 'melody', 'alice', 'andy', 'wanda', 'jim'] but got: {repr(users)}"
Slice`users to Return 3rd and 4th Elements

For the final task, we’ll extract a subsection from the users list to create the new center_users list. We can extract the third and fourth items from the list by slicing from 2 to 4.

using-lists.py (partial)

# 7) Slice the users lists to return the 3rd and 4th items and assign the result to `center_users`
center_users = users[2:4]

assert center_users == ['alice', 'andy'], f"Expected `users` to be ['alice', 'andy'] but got: {repr(center_users)}"

Additional Resources

Note: The using-lists.py file exists in the /home/cloud_user/ directory. If you do not see the file, please give the lab another minute to finish provisioning. If you prefer to use your own local Python editor, you can also access the initial using-lists.py file in the lab's GitHub repository.

From within the using-lists.py file, we'll be modifying the users list so that the assertions throughout the file all succeed eventually. As we're working through the tasks, we can run the file. Whenever Python gets to a line that starts with assert, it will raise an error and stop executing if we haven't met the criteria. The first error will look like this:

$ python3.7 using-lists.py
Traceback (most recent call last):
  File "s9-lists/using-lists-starter.py", line 3, in <module>
    assert users == [], f"Expected `users` to be [] but got: {repr(users)}"
NameError: name 'users' is not defined

This process will show us the line where the the script encountered an issue, and show us the differences between our expected and actual values.

Logging In

Using the Terminal To Complete the Lab

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the lab, log in with SSH, and use a text editor in the terminal, such as Vim.

Note: When copying and pasting code into Vim from the lab guide, first enter :set paste (and then i to enter insert mode) to avoid adding unnecessary spaces and hashes. To save and quit the file, press Escape followed by :wq. To exit the file without saving, press Escape followed by :q!.

Using VS Code To Complete the Lab

You can also access the lab using VS Code in the browser. If you'd like to go this route, then follow the steps below:

  1. Navigate to the public IP address of the workstation server (provided in your lab credentials) on port 8080, using http (e.g., http://PUBLIC_IP:8080).
  2. If you receive a notification indicating the connection is not secure, click Advanced. Then, proceed to the server.
  3. Use the password provided in your lab credentials.

Once you are in the server, open up using-lists.py (with either VS Code or a command-line text editor).

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?