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)

Slicing

Let’s play with slices. How do we get the last two elements of our list?

>>> my_list = ["h", "e", "l", "l", "o", "!"]
>>> len(my_list)
# So the last two indexes are 4 and 5. Since the first number in the slice is inclusive, and the second number is exclusive, we can ask for everything between index 4 and 6
>>> my_list[4:6]
# We can also say "Give me everything after index 4
>>> my_list[4:]
# Or, we can ask for just the last two items without caring how big the list is. This means "give me everything starting from two before the end":
>>> my_list[-2:]

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)

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}")
...

Converting Between Types

Converting between types in Python is one of the most powerful language features.

You can quickly convert between strings, numbers, and various data-types to supercharge quickly solving problems. You can even use powerful data structures like sets to your advantage.

Converting Between Numbers and Strings

Converting between numbers and strings is easy with str() and int():

>>> my_string = str(100)
>>> my_string
>>> type(my_string)
>>> my_int = int(my_string)
>>> my_int
>>> type(my_int)

You can also use float() to convert strings into floating point numbers:

>>> float("3.1415")
3.1415

Bonus tip: int() works great for converting floats as well, as long as you don’t care about the mantissa (the part after the decimal point):

>>> int(3.1415)

Converting Between Lists and Strings

A string can be considered as just a list of characters, so converting back and forth is easy:

>>> my_list = list("hello")
>>> my_list
>>> str(my_list)

Oops, that wasn’t quite what we wanted. Running any object through str() will usually return a literal string of that object. What we want is to join the elements of the list (into a string). We can do that using string’s built-in join() method. In this case, we’ll use an empty string:

>>> ''.join(my_list)
# Note: we can use any string we want to join the characters!
>>> ','.join(my_list)
>>> '-'.join(my_list)

Another common way of converting a string into a list is with the string’s split() method. This is useful for lightweight parsing of, for example, CSV (comma separated value) data.

>>> my_string = "the,quick,brown,fox"
>>> my_string.split(",")

Solutions

Comprehensions

Here's what you should have seen in your REPL:

Slicing

Here's what you should have seen in your REPL:

zip

Here's what you should have seen in your REPL:

Converting Between Types

Converting Between Numbers and Strings

Here's what you should have seen in your REPL:

Converting Between Lists and Strings

Here's what you should have seen in your REPL: