Code 401 Class 08 Reading Notes
List Comprehensions
Syntax
Three things are necessary for a python list comprehension to work.
- The expression we’d like to carry out. expression inside the square brackets.
- The object that the expression will work on. item inside the square brackets.
- An iterable list of objects to build our new list from. list inside the square brackets.
Understanding the list comprehension; you are going to perform an expression on each item in the list. The expression will determine what time is eventually stored in the output list.
Not only can you perform expressions on an entire list in a single line of code, but, it’s possible to add conditional statements in the form of filters, which allows for more precision in the way lists are handled.
Notes about Lists Comprehensions
- List comprehension methods are an elegant way to create and manage lists.
- In python, list comprehensions are a more compact way of creating lists.
- More flexible than for loops, list comprehension is usually faster than other methods.
Create a List with range()
Example:
# construct a basic list using range() and list comprehensions
# syntax
# [ expression for item in list ]
digits = [x for x in range(10)]
print(digits)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
First ‘x’ doesn’t do anything because we’re simply recording the number. The second ‘x’ represents each item in the list created by the range() method.
Create a List Using Loops and List Comprehension in Python
The first example is a loop, which is used to construct a list of the powers of two.
create a list and loop through it. Add an expression, we will raise x to the power of 2.
# create a list using a for loop
squares = []
for x in range(10):
# raise x to the power of 2
squares.append(x**2)
print(squares)
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Below will be an example of list comprehension with a fraction of a code.
# create a list using list comprehension
squares = [x**2 for x in range(10)]
print(squares)
Multiplying Parts of A list
Example of multiplying every number in a list by three in Python?
# create a list with list comprehensions
multiples_of_three = [ x*3 for x in range(10) ]
print(multiples_of_three)
Output:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
Adding a filter to the list compression allows for greater flexibility.
even_numbers = [ x for x in range(1,20) if x % 2 == 0]
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
Show the First letter of each word
# a list of the names of popular authors
authors = ["Ernest Hemingway","Langston Hughes","Frank Herbert","Toni Morrison",
"Emily Dickson","Stephen King"]
# create an acronym from the first letter of the author's names
letters = [ name[0] for name in authors ]
print(letters)
Output:
['E', 'L', 'F', 'T', 'E', 'S']
Example separating the characters in a string
# use list comprehension to print the letters in a string
letters = [ letter for letter in "20,000 Leagues Under The Sea"]
print(letters)
Output:
['2', '0', ',', '0', '0', '0', ' ', 'L', 'e', 'a', 'g', 'u', 'e', 's', ' ', 'U', 'n', 'd', 'e', 'r', ' ', 'T', 'h', 'e', ' ', 'S', 'e', 'a']
Print numbers only from a given string
Using isdigit method, we can extract the phone number from the user data.
Example:
# user data entered as name and phone number
user_data = "Elvis Presley 987-654-3210"
phone_number = [ x for x in user_data if x.isdigit()]
print(phone_number)
Output:
['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']
Parsing a file using list comprehension
Using a list comprehension, we can iterate through the lines of a text in the file and store their contents in a new list.
Example of file called dreams.txt:
# open the file in read-only mode
file = open("dreams.txt", 'r')
poem = [ line for line in file ]
for line in poem:
print(line)
Output:
Hold fast to dreams
For if dreams die
Life is a broken-winged bird
That cannot fly.
-Langston Hughs
Using functions in list comprehensions
Example:
# list comprehension with functions
# create a function that returns a number doubled
def double(x):
return x*2
nums = [double(x) for x in range(1,10)]
print(nums)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
Adding filter element from the list using additional arguments:
# add a filter so we only double even numbers
even_nums = [double(x) for x in range(1,10) if x%2 == 0]
print(even_nums)
Output:
[4, 8, 12, 16]
More complex logic using additional arguments
nums = [x+y for x in [1,2,3] for y in [10,20,30]]
print(nums)
Output:
[11, 21, 31, 12, 22, 32, 13, 23, 33]
Things I want to know more about
That last example is/was a little hard for me to fully comprehend. So the first element of x adds into the first, second, third element of y. Then it moves to the second element of x, and adds y elements, first, second and third. Then finally, the third x element adds into y’s first, second, and third element?