Python – Trim tuples by K

When it is required to trim tuples based on a K value, a simple iteration and the 'append' method is used. Trimming removes K elements from both the beginning and end of each tuple.

Example

The following code demonstrates how to trim tuples by removing the first and last K elements ?

my_list = [(44, 3, 68, 11, 5), (68, 44, 9, 5, 8), (8, 11, 2, 68, 5), (44, 68, 2, 5, 7)]

print("The list is :")
print(my_list)

K = 1
print("The value for K is")
print(K)

my_result = []

for element in my_list:
    list_length = len(element)
    my_result.append(tuple(list(element)[K: list_length - K]))

print("The resultant list is :")
print(my_result)

Output

The list is :
[(44, 3, 68, 11, 5), (68, 44, 9, 5, 8), (8, 11, 2, 68, 5), (44, 68, 2, 5, 7)]
The value for K is
1
The resultant list is :
[(3, 68, 11), (44, 9, 5), (11, 2, 68), (68, 2, 5)]

How It Works

The algorithm follows these steps ?

  • A list of tuples is defined and displayed on the console.

  • The value for K is defined and displayed on the console.

  • An empty list is created to store the trimmed tuples.

  • The list is iterated over and the length of every tuple is calculated.

  • Elements from index K to (length - K) are extracted using slicing and converted to a tuple.

  • The trimmed tuple is appended to the result list.

  • The final result is displayed on the console.

Alternative Method Using List Comprehension

A more concise approach using list comprehension ?

my_list = [(44, 3, 68, 11, 5), (68, 44, 9, 5, 8), (8, 11, 2, 68, 5), (44, 68, 2, 5, 7)]

print("The original list is :")
print(my_list)

K = 2
print("The value for K is :", K)

# Using list comprehension
my_result = [tuple(element[K:-K]) for element in my_list if len(element) > 2*K]

print("The trimmed list is :")
print(my_result)
The original list is :
[(44, 3, 68, 11, 5), (68, 44, 9, 5, 8), (8, 11, 2, 68, 5), (44, 68, 2, 5, 7)]
The value for K is : 2
The trimmed list is :
[(68,), (9,), (2,), (2,)]

Conclusion

Trimming tuples by K removes K elements from both ends of each tuple. Use list comprehension for a concise approach or explicit loops for better readability. Always ensure the tuple length is greater than 2*K to avoid empty results.

Updated on: 2026-03-26T00:54:16+05:30

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements