Last Updated : 19 Dec, 2024
Python's list comprehension and slicing are powerful tools for handling and manipulating lists. When combined, they offer a concise and efficient way to create sublists and filter elements. This article explores how to use list comprehension with slicing including practical examples.
The syntax for using list comprehension with slicing is:
Parameters:[expression for item in list[start:stop:step] if condition]
Doubling elements in a Slice avoids altering the original list, making it useful when working with immutable data or creating variations for analysis.
Python
a = [1, 2, 3, 4, 5]
# Create a new list where each element in the
#first 3 elements of 'a' is multiplied by 2
result = [x * 2 for x in a[:3]]
print(result)
Explanation:
nums[:3]
selects the first three elements of the list [1, 2, 3]
.x * 2
doubles each element in the sliced list.[2, 4, 6]
.This approach combines slicing to isolate the desired range of elements with a conditional statement to select only even numbers. It is particularly useful in tasks such as preprocessing numerical data or filtering inputs for computations.
Python
a = [1, 2, 3, 4, 5, 6]
# Filter even numbers from the last three elements
evens = [x for x in a[-3:] if x % 2 == 0]
print(evens)
Explanation:
nums[-3:]
selects the last three elements of the list [4, 5, 6]
.if x % 2 == 0
filters out numbers that are not even.Using a step value in slicing allows us to skip elements at defined intervals. Combining this with list comprehension helps create patterned subsets, or simplifying repetitive patterns in a list.
Python
# Extract squares of alternate elements
a = [1, 2, 3, 4, 5]
squared = [x**2 for x in a[::2]]
print(squared)
Explanation:
nums[::2]
selects every alternate element, starting from the first ([1, 3, 5]
).x**2
squares each element in the selected sublist.Nested list comprehensions paired with slicing offer a powerful way to manipulate data in multi-dimensional lists. This is especially useful for matrix operations or extracting and transforming specific portions of nested data structures.
a = [[1, 2], [3, 4], [5, 6]]
# Flatten a 2D list after slicing
b = [y for row in a[:2] for y in row]
print(b)
Explanation:
matrix[:2]
selects the first two sublists from the 2D list [[1, 2], [3, 4]]
.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4