List
comprehensionThis is a special syntax in Python. We use an expression in square brackets to create a new list. We base the list on an existing collection (an iterable
).
With this syntax, we perform a transformation on each element in an iterable
. A new list is returned. We can use an if
-clause to remove elements in the list comprehension.
This example uses a mathematical expression (n times 10) to transform a list. A new, separate, list is created. The existing list (numbers) is left alone.
numbers = [10, 20, 30] # Use list comprehension to multiply all numbers by 10. # ... They are placed in a new list. result = [n * 10 for n in numbers] print(result)[100, 200, 300]
In this example we use list comprehension to create a list of HTML strings. We apply the html()
method on each string
in the input list.
string
is given the identifier "x." Html()
is called on each element in the list.# Transform string into HTML. def html(s): return "<b>" + s.capitalize() + "</b>" # Input string. input = ["rabbit", "mouse", "gorilla", "giraffe"] # List comprehension. list = [html(x) for x in input] # Result list. print(list)['<b>Rabbit</b>', '<b>Mouse</b>', '<b>Gorilla</b>', '<b>Giraffe</b>']
When using a list comprehension, it is possible to apply an if
-statement. It will only add elements that are greater than 10 in the numbers list.
numbers = [10, 20, 30, 40] print(numbers) # Use if-statement within a list comprehension. # ... This first eliminates numbers less than or equal to 10. # ... Then it changes elements in the list comprehension. result = [n * 10 for n in numbers if n > 10] print(result)[10, 20, 30, 40] [200, 300, 400]
for
-loopIs a list comprehension blazing fast? This is not easy to answer. But my findings indicate it is similar in speed to copying and modifying an existing iterable
.
for-in
loop to modify those elements.for-in
loop with range()
to modify the elements performed faster.import time # For benchmark. source = [0, 1, 2, 3, 4, 5] print(time.time()) # Version 1: create list comprehension. for i in range(0, 10000000): values = [n * 10 for n in source] if values[5] != 50: break print(time.time()) # Version 2: copy array and multiply values in loop. for i in range(0, 10000000): values = source[:] for v in range(0, len(values)): values[v] = values[v] * 10 if values[5] != 50: break print(time.time())1440121192.57 1440121193.739 1.16900014877 s: list comprehension 1440121194.668 0.92899990081 s: copy list and for-in
List
comprehension is a powerful syntax for modifying individual elements from an iterable
. With an if
-clause, we can only add certain elements into a list comprehension.