Slice a 2D List in Python
Last Updated :
14 Feb, 2024
Slicing a 2D list in Python is a common task when working with matrices, tables, or any other structured data. It allows you to extract specific portions of the list, making it easier to manipulate and analyze the data. In this article, we'll explore four simple and commonly used methods to slice a 2D list in Python.
How To Slice A 2D List In Python?
Below, are the methods of How To Slice A 2D List In Python.
Create 2D List
First we created the 2D list name matrix , and print the 2D list.
Python3
# Sample 2D list
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix)
Output[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Slice A 2D List In Python Using Basic Slicing
The first code extracts rows from index 1 to 2 (exclusive) of a 2D list named 'matrix' and assigns the result to the variable 'rows_slice'. The second code creates a new list 'columns_slice' by slicing columns from index 0 to 2 (exclusive) in all rows of the 'matrix'.
Python3
# Slicing rows from index 1 to 2 (exclusive)
rows_slice = matrix[1:2]
print("Sliced Rows:", rows_slice)
# Slicing columns from index 0 to 2 (exclusive) in all rows
columns_slice = [row[0:2] for row in matrix]
print("Sliced Columns:", columns_slice)
Output
Sliced Rows: [[4, 5, 6]]
Sliced Columns: [[1, 2], [4, 5], [7, 8]]
Slice A 2D List In Python Using Condition Statement
In this example, below code extracts rows from a matrix where at least one element is greater than 5 and prints them. Similarly, it extracts columns from the matrix whose sum is greater than 10 and prints them.
Python3
# Slicing rows based on a condition (e.g., elements greater than 5)
rows_condition = [row for row in matrix if any(element > 5 for element in row)]
print("Rows with Elements > 5:", rows_condition)
# Slicing columns based on a condition (e.g., columns with sum greater than 10)
columns_condition = [col for col in zip(*matrix) if sum(col) > 10]
print("Columns with Sum > 10:", columns_condition)
Output
Rows with Elements > 5: [[4, 5, 6], [7, 8, 9]]
Columns with Sum > 10: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Slice A 2D List In Python Using Itertools Function
In this example below code uses `islice` from the `itertools` module to slice rows and columns from a matrix. It extracts a specific range of rows (1 to 2) and a specific range of elements (0 to 2) from each row and prints them as sliced rows and columns, respectively.
Python3
from itertools import islice
# Slicing rows using itertools.islice
rows_islice = list(islice(matrix, 1, 2))
print("islice Sliced Rows:", rows_islice)
# Slicing columns using itertools.islice
columns_islice = [list(islice(row, 0, 2)) for row in matrix]
print("islice Sliced Columns:", columns_islice)
Output
islice Sliced Rows: [[4, 5, 6]]
islice Sliced Columns: [[1, 2], [4, 5], [7, 8]]
Slice A 2D List In Python Using NumPy Library
In this example, below code converts a list named 'matrix' into a NumPy array ('matrix_np') and then uses NumPy slicing to extract a specific range of rows (1 to 2) and a specific range of columns (0 to 2). The sliced rows and columns are printed as 'NumPy Sliced Rows' and 'NumPy Sliced Columns', respectively.
Python3
import numpy as np
# Convert the list to a NumPy array
matrix_np = np.array(matrix)
# Slicing rows using NumPy
rows_slice_np = matrix_np[1:2, :]
print("NumPy Sliced Rows:", rows_slice_np)
# Slicing columns using NumPy
columns_slice_np = matrix_np[:, 0:2]
print("NumPy Sliced Columns:", columns_slice_np)
Output
NumPy Sliced Rows: [[4 5 6]]
NumPy Sliced Columns: [[1 2]
[4 5]
[7 8]]
Conclusion
In conclusion, slicing a 2D list in Python allows for efficient extraction of specific elements or sublists based on specified ranges. The syntax for slicing involves using square brackets and colons to denote start, stop, and step parameters. This powerful feature enhances code readability and simplifies data manipulation tasks, providing a convenient way to access and manipulate elements within a two-dimensional structure.
Similar Reads
Slice a 2D Array in Python
We are given a 2D array matrix and we have to Slice this matrix 2D array and return the result. In this article, we will see how we can Slice the 2D array in Python. Example Input : matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output : [[ 4, 5, 6]] Explanation : We can see that 2D array (matrix) is
3 min read
Python | Sliced Product in List
Accessing elements in a list has many types and variations. These are an essential part of Python programming and one must know to perform the same. This article discusses ways to fetch the initial K elements and do its multiplication. Letâs discuss a certain solution to perform this task. Method #1
5 min read
How to Split Lists in Python?
Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read
Python - Convert 2D list to 3D at K slicing
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[
4 min read
Python - Ways to Flatten a 2D list
We are given a 2D list we need to flatten that given list. For example, a = [[1, 2, 3], [4, 5], [6, 7, 8]] we need to flatten it so that the output becomes [1, 2, 3, 4, 5, 6, 7, 8].Using a Nested LoopA nested loop iterates over each sublist in the 2D list and then over each element in the sublist ap
3 min read
Check for Sublist in List-Python
The task of checking for a sublist in a list in Python involves determining whether a given sequence of elements (sublist) appears consecutively within a larger list. This is a common problem in programming, particularly in data processing and pattern matching. For example, if we have a list [5, 6,
4 min read
How To Slice A List Of Tuples In Python?
In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently. Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or steps within the list of tuples. This technique is particularly handy when dealing with datasets or organizing i
3 min read
Use of slice() in Python
In Python, slice() is used to access a portion of a sequence such as a list or tuple. It helps improve code readability and maintainability by giving meaningful names to slices instead of using hardcoded indices. For example: slice(1, 5, 2) corresponds to a[1:5:2] and slice(1, 4) corresponds to a[1:
3 min read
Python - Truncate a list
We are given a list we need to truncate list. For example, we are having a list a = [1, 2, 3, 4, 5] we need to truncate (removing 2 elements from behind) list so that the output should be [1,2,3].Using List SlicingList slicing allows truncating a list by specifying the starting and ending indices.Py
2 min read
Python | Split list in uneven groups
Sometimes, while working with python, we can have a problem of splitting a list. This problem is quite common and has many variations. Having solutions to popular variations proves to be good in long run. Let's discuss certain way to split list in uneven groups as defined by other list. Method 1: Us
6 min read