Ranges and List Comprehensions

Question Click to View Answer

What does the following code return?

list(range(5))

[0, 1, 2, 3, 4] is returned.

The range() function creates collections that can converted to lists or used with for loops.

What does the following code return?

list(range(3, 7))

[3, 4, 5, 6] is returned.

The range() function can be supplied two arguments to indicate when the range should start and when it should end.

What does the following code return?

type(range(100))

<class 'range'> is returned.

The range() function creates range objects that make it easy to work with sequences of numbers.

What does the following code return?

list(range(100, 300, 50))

[100, 150, 200, 250] is returned.

The range() function can take an optional third argument to specify the difference between each number in the sequence (referred to as the "step").

What does the following code return?

list(range(10, 0, -2))

[10, 8, 6, 4, 2] is printed.

Descending ranges can also be constructed.

What does the following code print?

r = [x ** 2 for x in range(5)]
print(r)

[0, 1, 4, 9, 16] is printed.

This code squares all the numbers in range(5).

This code is an example of a list comprehension. List comprehensions are elegant ways to create lists from other lists.

What does the following code print?

r = [2 ** i for i in range(5)]
print(r)

[1, 2, 4, 8, 16] is printed.

This code raises 2 to all the numbers in range(5).

This is another example that uses the list comprehension syntax.

What does the following code print?

r = [x for x in range(10) if x % 2 == 0]
print(r)

[0, 2, 4, 6, 8] is printed.

This example uses a list comprehension to make a list with all the even numbers in range(10). if statements can be used with list comprehensions.

What does the following code print?

r = [(x, y) for x in range(2) for y in range(2)]
print(r)

[(0, 0), (0, 1), (1, 0), (1, 1)] is printed.

This example uses a list comprehension to create a list of tuples.