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]
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.
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 thestopvalue (e.g.,range(5)will cause a for loop to iterate from 0 to 4, right before 5)start: Iteration will begin at thestartvalue (e.g.,range(1, 5)will cause a for loop to iterate beginning from 1 to 4, right before 5); default is0step: 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 is1- backwards counting is possible by setting the
stepvalue as-1
- backwards counting is possible by setting the
This means that range(0, 6, 1) will iterate from 0 to 5, which make up the contents of our list.
Hence, len([0, 1, 2, 3, 4, 5]) becomes 6, because this list contains 6 elements in total.