Question
In the context of this exercise, how does this list comprehension in the example work?
[t*element + w*n for element in range(d)]
Answer
The list comprehension provided in the example code returns a list of x values for the bar locations in the graph.
There are 4 variables which will let us do this:
n
determines which dataset it is currently for.
t
determines the total number of datasets to graph side by side.
d
tells us how many bars there are per dataset.
w
tells us the width of each individual bar.
If we take the provided values for the first dataset China Data
, we get
[2*element + 0.8*1 for element in range(7)]
This essentially means, for each element in range(7)
, construct a list where each element is
2*element + 0.8
This would give us this list of values,
[0.8, 2.8, 4.8, 6.8, 8.8, 10.8, 12.8]
If we change n
to 2 for the second dataset US Data
, it gives us the list
[1.6, 3.6, 5.6, 7.6, 9.6, 11.6, 13.6]
These x values will position each pair of bars for each set of data next to each other in a clear way.