The first exercise at the end of the chapter is to replace
1 | [i for i in range(3)] + [j for j in range(8,11)]
|
by a single list comprehension. In Python2, there is a nearly trivial solution:
1 | [i for i in range(3)+range(8,11)]
|
However, this won't work in Python3, because range() is a generator-like object rather than a list. What the exercise seems to ask is forming the union of two list comprehensions. What one might think of first is not valid Python3:
1 | [i for i in range(3) "or in" range(8,11) ]
|
Unfortunately, "or in" is not an operator we can use. Instead of trying the union idea, it's plausible to use intersection. The approach of negative description is appropriate here. Something like:
1 | [i for i in range(11) "except if in" range(4,8) ]
|
(Still not Python3 syntax, but turns out to be a helpful step in problem-solving.) Using a conditional list comprehension enables the idea to be expressed:
1 | [i for i in range(11) if i not in range(4,8) ]
|