Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Remove positional rows
When you need to remove rows from a list by their positions, you can use the pop() method with iteration. The key is to iterate in reverse order to avoid index shifting issues when removing multiple elements.
Example
Below is a demonstration of removing rows at specific positions −
my_list = [[31, 42, 2], [1, 73, 29], [51, 3, 11], [0, 3, 51], [17, 3, 21], [1, 71, 10], [0, 81, 92]]
print("The list is:")
print(my_list)
my_index_list = [1, 2, 5]
for index in my_index_list[::-1]:
my_list.pop(index)
print("The output is:")
print(my_list)
The list is: [[31, 42, 2], [1, 73, 29], [51, 3, 11], [0, 3, 51], [17, 3, 21], [1, 71, 10], [0, 81, 92]] The output is: [[31, 42, 2], [0, 3, 51], [17, 3, 21], [0, 81, 92]]
How It Works
The process involves these steps:
- A nested list with 7 rows is defined and displayed
- Index positions
[1, 2, 5]are specified for removal - The indices are reversed using
[::-1]to get[5, 2, 1] - Each index is removed using
pop()starting from the highest index - This prevents index shifting that would occur if removing from left to right
Alternative Method Using List Comprehension
You can also create a new list excluding unwanted positions −
my_list = [[31, 42, 2], [1, 73, 29], [51, 3, 11], [0, 3, 51], [17, 3, 21], [1, 71, 10], [0, 81, 92]]
indices_to_remove = [1, 2, 5]
result = [row for i, row in enumerate(my_list) if i not in indices_to_remove]
print("Result using list comprehension:")
print(result)
Result using list comprehension: [[31, 42, 2], [0, 3, 51], [17, 3, 21], [0, 81, 92]]
Key Points
-
Reverse iteration: Always iterate indices in reverse order when using
pop() - Index shifting: Removing elements from left to right changes subsequent indices
- List comprehension: Creates a new list, preserving the original
Conclusion
Use pop() with reverse iteration to remove positional rows in-place. For a functional approach that preserves the original list, use list comprehension with enumerate().
Advertisements
