list comprehensions
The Python list comprehensions are a very easy way to apply a function or filter to a list of items. List comprehensions can be very useful if used correctly but very unreadable if you're not careful.
Let's dive right into a few examples. The basic premise of a list comprehension looks like this:
>>> squares = [x ** 2 for x in range(10)] >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
We can easily expand this with a filter:
>>> uneven_squares = [x ** 2 for x in range(10) if x % 2] >>> uneven_squares [1, 9, 25, 49, 81]
The syntax is pretty close to regular Python for loops, but the if statement and automatic storing of results makes it quite useful for some cases. The regular Python equivalent is not much longer, however:
>>> uneven_squares = [] >>> for x in range(10): ... if x % 2: ... uneven_squares.append(x ** 2) >>> uneven_squares [1, 9, 25, 49, 81]
Care must be taken though; because...