Python List Comprehension with Slicing (original) (raw)
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:
**[expression for item in list[start:stop:step] if condition]
Parameters:
- **expression: The operation or transformation to apply to elements.
- **item: The current element from the sliced portion of the list.
- **list[start:stop:step]: The sliced part of the list.
- **condition (optional): A filter to include specific elements.
Return Type:
- The return type of list comprehension with slicing is a **list.
- **List: The operation results in a new list that is created by applying the expression to the elements of the sliced portion of the original list (optionally filtered by a condition).
Doubling Elements in a Slice
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:
- slicing
nums[:3]
selects the first three elements of the list[1, 2, 3]
. - expression
x * 2
doubles each element in the sliced list. - result is a new list containing the doubled values
[2, 4, 6]
.
Filtering Even Numbers from a Slice
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:
- The slicing
nums[-3:]
selects the last three elements of the list[4, 5, 6]
. - The condition
if x % 2 == 0
filters out numbers that are not even.
Using Step in Slicing
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:
- The slicing
nums[::2]
selects every alternate element, starting from the first ([1, 3, 5]
). - The expression
x**2
squares each element in the selected sublist.
Nested List Comprehension with Slicing
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.
Python `
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:
- The slicing
matrix[:2]
selects the first two sublists from the 2D list[[1, 2], [3, 4]]
. - The nested list comprehension iterates over each row and then over each element in the row.
Similar Reads
- Python Lists In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s 6 min read
- Get a list as input from user in Python We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python. Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a si 3 min read
- Create List of Numbers with Given Range - Python The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 3 min read
- Python - Add List Items Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples: Add a Single Item Using append()append() method adds one item to the end of the l 3 min read
- How to add Elements to a List in Python In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method: [GFGTABS] Python a = [1, 2, 3] a.ap 2 min read