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:
- Takes a string in
usernames
- Assigns that string to a variable called
user
- Adds “ please follow me!” to
user
- Appends that concatenation to the new list called
messages
- 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:
- Takes a number in
my_upvotes
- Assigns that number to a variable called
vote_value
- Adds 100 to
vote_value
- Appends that sum to the new list
updated_upvotes
- 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
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
Print fahrenheit
.