In this Python article we are going to talk about Exploring Power of List Comprehensions in Python, Python is powerful programming language that offers different tools and techniques for solving complex problems. one of those tool is the use of list comprehensions. using list comprehension we can easily create lists in Python, because they allow us to create new list by applying a function or expression to each element in an existing list.
In this article we are going to explore the power of list comprehensions in Python and how they can be used to simplify code and solve problems more efficiently.
What is List Comprehension?
List comprehension is a way to create new list by iterating over an existing list and applying an operation to each element. syntax of list comprehension is like this:
1 |
new_list = [expression for item in iterable] |
The expression is the operation to be applied to each item in the iterable, and item is the variable that represents each element in the iterable. iterable is any object that can be iterated over such as list, tuple or string.
Now let’s create practical example, in the example we have a list of numbers and we want to create a new list with each number squared:
1 2 3 |
numbers = [1, 2, 3, 4, 5] squared_numbers = [num**2 for num in numbers] print(squared_numbers) |
In this example we have used list comprehension to iterate over the numbers list and square each element using expression num**2. resulting list, squared_numbers, contains the squared values of each number in the numbers list.
Run the code and this will be the result
Filtering with List Comprehensions
in addition to transforming each element in a list, list comprehensions can also be used to filter elements based on a condition. syntax for filtering with list comprehensions is as follows:
1 |
new_list = [expression for item in iterable if condition] |
The condition is an expression that evaluates to Boolean value (True or False) and determines whether or not to include the item in the new list.
For example let’s say we have a list of numbers and we want to create a new list with only the even numbers:
1 2 3 |
numbers = [1, 2, 3, 4, 5] even_numbers = [num for num in numbers if num % 2 == 0] print(even_numbers) |
In this example we have used list comprehension to iterate over the numbers list and include only the even numbers using the condition num % 2 == 0.
Run the code and this is the result
Nested List Comprehensions
Also you can use nested list comprehension and this is the syntax.
1 |
new_list = [expression for item in iterable if condition for nested_item in nested_iterable if nested_condition] |
For example let’s say we have a list of lists and we want to create a new list with only even numbers:
1 2 3 |
nested_numbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] even_numbers = [num for sublist in nested_numbers for num in sublist if num % 2 == 0] print(even_numbers) |
Run the code and this is the result