# 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.

Below is a demonstration of the same −

## Example

Live Demo

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)]

## Explanation

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

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

• An empty list is defined.

• The list is iterated over and the length of every element is stored in a variable.

• The elements from K to difference between length of list and K are accessed using indexing, and converted to a tuple.

• This is appended to the empty list.

• This is displayed as output on the console.

Advertisements