Practice

Comprehensions

Let’s practice our comprehensions. Create a list of only odd numbers between 0 and 100 using a list comprehension. Then, use a comprehension to create a dictionary where the keys are the even numbers from your list, and the values are random integers between 0 and 100 (hint: try random.randint(min, max)). Finally, use a comprehension to create a set of every unique value from the above dictionary.

>>> my_list = [num for num in range(0, 100) if num % 2 == 0]
>>> print(my_list)

>>> import random
>>> my_dict = {num:random.randint(0, 100) for num in my_list}
>>> print(my_dict)

>>> my_set = {num for num in my_dict.values()}
>>> print(my_set)
Here's what you should have seen in your REPL:

Slicing

You know how to create a list of even or odd numbers with a list comprehension. Make a list of numbers between 0 and 100, then try making a list of even numbers between 30 and 70, by taking a slice from the first list. Then, make a new list in the reverse order.

>>> my_list = [num for num in range(0, 100)]
>>> my_slice = my_list[30:70:2]
>>> print(my_slice)
>>> my_backwards_slice = my_slice[::-1]
>>> print(my_backwards_slice)
Here's what you should have seen in your REPL:

zip

Make a list of all the names you can think of, called “names”. Make a second list of numbers, called “scores”, using a list comprehension and random.randint(min, max) as before. Use the first list in your comprehension to make it the same length. Then, use zip() to output a simple scoreboard of one score per name.

>>> names = ["Nina", "Max", "Floyd", "Lloyd"]
>>> scores = [random.randint(0, 100) for name in names]
>>> scores
[41, 38, 96, 81]
>>> for name, score in zip(names, scores):
...     print(f"{name} got a score of {score}")
...
Here's what you should have seen in your REPL: