C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Expression: Before the "for" in the list comprehension, we can apply any expression. This can be a function call. A value must be returned.
Math: In examples, math expressions are often used. But in real programs, consider methods that prepend or append strings.
Python program that uses list comprehension
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)
Output
[100, 200, 300]
Lambda: 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.
Python program that uses filter, list comprehension
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)
Output
[10, 20, 30, 40]
[200, 300, 400]
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.
Copy ListPython program that benchmarks list comprehension, for loop
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())
Output
1440121192.57
1440121193.739 1.16900014877 s: list comprehension
1440121194.668 0.92899990081 s: copy list and for-in
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.