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
Remove Tuples of Length K in Python
When working with lists of tuples, you may need to remove tuples based on their length. Python provides several approaches to filter out tuples of a specific length K.
Using List Comprehension
List comprehension offers a concise way to filter tuples by length ?
my_list = [(32, 51), (22, 13), (94, 65, 77), (70, ), (80, 61, 13, 17)]
print("The list is:")
print(my_list)
K = 1
print("The value of K is:", K)
my_result = [ele for ele in my_list if len(ele) != K]
print("The filtered list is:")
print(my_result)
The list is: [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)] The value of K is: 1 The filtered list is: [(32, 51), (22, 13), (94, 65, 77), (80, 61, 13, 17)]
Using filter() Function
The filter() function provides an alternative approach ?
my_list = [(32, 51), (22, 13), (94, 65, 77), (70, ), (80, 61, 13, 17)]
K = 2
print("Original list:", my_list)
print("Removing tuples of length:", K)
# Using filter with lambda
my_result = list(filter(lambda x: len(x) != K, my_list))
print("Filtered list:", my_result)
Original list: [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)] Removing tuples of length: 2 Filtered list: [(94, 65, 77), (70,), (80, 61, 13, 17)]
Using a Loop
A traditional loop approach for better readability ?
my_list = [(32, 51), (22, 13), (94, 65, 77), (70, ), (80, 61, 13, 17)]
K = 3
print("Original list:", my_list)
my_result = []
for tuple_item in my_list:
if len(tuple_item) != K:
my_result.append(tuple_item)
print("After removing tuples of length", K)
print("Result:", my_result)
Original list: [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)] After removing tuples of length 3 Result: [(32, 51), (22, 13), (70,), (80, 61, 13, 17)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Simple filtering |
| filter() | Medium | Fast | Functional programming |
| Loop | High | Slower | Complex logic |
Conclusion
List comprehension is the most Pythonic and efficient method for removing tuples of specific length. Use filter() for functional programming style or loops when additional processing is needed during iteration.
Advertisements
