List ComprehensionUse list comprehension to change elements in lists. Modify entire lists in one statement.
This page was last reviewed on Jul 6, 2023.
List comprehension. This is a special syntax form 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 functions like filter to remove elements in the list comprehension.
String Reverse
First example. 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.
Note Before the "for" in the list comprehension, we can apply any expression. This can be a function call. A value must be returned.
Note 2 In examples, math expressions are often used. But in real programs, consider methods that prepend or append strings.
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]
HTML example. 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.
Note In this list comprehension, each string is given the identifier "x." Html() is called on each element in the list.
Info In list comprehension, we apply a method to each element. The syntax is short, making it easier to read.
# 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>']
Filter example. A list comprehension cannot remove elements (or add them). But we can use filter() to modify the elements returned from an iterable (like an existing list).
Detail We apply a lambda expression here. It will filter out elements that are less than or equal to 10 in the numbers list.
Result Our list comprehension multiplies all the numbers returned by filter by 10. So we get a filtered, transformed list.
numbers = [10, 20, 30, 40] print(numbers) # Use filter built-in 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 filter(lambda n: n > 10, numbers)] print(result)
[10, 20, 30, 40] [200, 300, 400]
Performance versus for-loop. Is 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.
Version 1 Uses a list comprehension. It multiples the six elements in the array by 10 and then tests the sixth element at index 5.
Version 2 Uses a total-list slice to copy the list. Then uses a for-in loop to modify those elements.
List Copy
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
Performance, results. The version 2, which copies the list and uses a for-in loop with range() to modify the elements performed faster. The difference though was small.
So The list comprehension had clearer syntax, and only a slight performance reduction. It is probably a preferable solution.
Note I used PyPy, which is a Python compiler. For other versions of Python, please run the test for optimal results.
List comprehension is a powerful syntax form for modifying individual elements from an iterable. With filter, we can add or remove elements placed into a list comprehension.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 6, 2023 (edit).
© 2007-2024 Sam Allen.