HomeSearch

Python List Comprehension

Use list comprehension to change elements in lists. Modify entire lists in one statement.

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.List

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.Initialize list

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]

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.

Identifier: 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.

Python program that uses list comprehension # 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) Output ['<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).

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]

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.

Copy List
Python 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

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.

A review. 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.