Skip to Content
Learn
Loops
More List Comprehensions

Let’s say we’re working with the usernames list from the last exercise:

>>> print(usernames) ["@coolguy35", "@kewldawg54", "@matchamom"]

We want to create a new list with the string " please follow me!" added to the end of each username. We want to call this new list messages. We can use a list comprehension to make this list with one line:

messages = [user + " please follow me!" for user in usernames]

This list comprehension:

  1. Takes a string in usernames
  2. Assigns that string to a variable called user
  3. Adds “ please follow me!” to user
  4. Appends that concatenation to the new list called messages
  5. Repeats steps 1-4 for all of the strings in usernames

Now, messages contains these values:

["@coolguy35 please follow me!", "@kewldawg54 please follow me!", "@matchamom please follow me!"]

Being able to create lists with modified values is especially useful when working with numbers. Let’s say we have this list:

my_upvotes = [192, 34, 22, 175, 75, 101, 97]

We want to add 100 to each value. We can accomplish this goal in one line:

updated_upvotes = [vote_value + 100 for vote_value in my_upvotes]

This list comprehension:

  1. Takes a number in my_upvotes
  2. Assigns that number to a variable called vote_value
  3. Adds 100 to vote_value
  4. Appends that sum to the new list updated_upvotes
  5. Repeats steps 1-4 for all of the numbers in my_upvotes

Now, updated_upvotes contains these values:

[292, 134, 122, 275, 175, 201, 197]

Instructions

1.

We have provided a list of temperatures in celsius. Using a list comprehension, create a new list called fahrenheit that converts each element in the celsius list to fahrenheit.

*Note: * To convert, use the formula:

temperature_in_fahrenheit = temperature_in_celsius * 9/5 + 32
2.

Print fahrenheit.

Folder Icon

Sign up to start coding

Already have an account?