Skip to content

Question 15

The following Python expression is entered into a fresh Python shell with no prior import statements. Determine the result from evaluating the following expression. [3 marks]

print(len([x for x in range(0, 6, 1)]))
Solution

This expression requires finding out the length of a given list created using list comprehension. First, we need to figure out the contents of the list [x for x in range(0, 6, 1)].

Like how for loops work, the familiar syntax is not just for show. Think of this as a rephrasing of the familiar for loop structure you may have been used to.

l = []  # assume we gave this list a name
for x in range(0, 6, 1):
    l.append(x)

Recall how the range() function works - it takes in between 1 to 3 parameter inputs:

  • 1 input: (stop)
  • 2 inputs: (start, stop)
  • 3 inputs: (start, stop, step)

Depending on how many parameters you put into the range function, you will use some if not all of the following:

  • stop: Iterate until before the stop value (e.g., range(5) will cause a for loop to iterate from 0 to 4, right before 5)
  • start: Iteration will begin at the start value (e.g., range(1, 5) will cause a for loop to iterate beginning from 1 to 4, right before 5); default is 0
  • step: Dictates the progression of the range (e.g., range(1, 5, 2) will cause a for loop to count up every 2 value units from 1 up till before 5); default is 1
    • backwards counting is possible by setting the step value as -1

This means that range(0, 6, 1) will iterate from 0 to 5, which make up the contents of our list.

[x for x in range(0, 6, 1)] == [0, 1, 2, 3, 4, 5]

Hence, len([0, 1, 2, 3, 4, 5]) becomes 6, because this list contains 6 elements in total.

Answer
6