Exchange the Given for Loop for a Comprehension

1 hour
  • 3 Learning Objectives

About this Hands-on Lab

In this lab, you are given a nested `for` loop that calls a function and asked to convert it to a `list` comprehension.

You should have basic Python skills and understand `for` loops as well as basic information about comprehensions.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Accessing the Code Server and Python File

Use the public IP address of your public server in the URL line of your browser, and add :8080. It should look like 1.1.1.1:8080. Open the file lab1.py and make sure the Python interpreter is set for Python 3.8.2. If messages appear that the linter is not installed, just dismiss them.

Write a list Comprehension to Replace the for Loop Given

Create a new function with the same name as the for loop function. Then prepend old_ to the for loop function name.

Write the code comprehension that will replace the for loop.

Test the list Comprehension

Test that the for loop function and the list comprehension function return the same results.

Additional Resources

Logging In

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab overview page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. If you'd like to go this route, then you will need to navigate to the public IP address of the workstation server (provided in the hands-on lab overview page) on port 8080 (example: http://PUBLIC_IP:8080). Your password will be the same password that you'd use to connect over SSH.

Completing the Lab

On your server is a file lab1.py. Using that file, refactor the for loop into a comprehension. Make sure to keep and rename the original functions. Finally, test that the original functions and your new comprehension provide the same result.

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?