
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Trim tuples by N elements in Python
- Python program to find tuples which have all elements divisible by K from a list of tuples
- Remove Tuples of Length K in Python
- Python – Filter Tuples Product greater than K
- Extract tuples having K digit elements in Python
- Python – Remove Tuples with difference greater than K
- Python – Sort Tuples by Total digits
- Sort Tuples by Total digits in Python
- Find top K frequent elements from a list of tuples in Python
- Sort list of tuples by specific ordering in Python
- Python program to Sort Tuples by their Maximum element
- Filter Tuples by Kth element from List in Python
- Python - Restrict Tuples by frequency of first element’s value
- List expansion by K in Python
- Python – Sort row by K multiples

Advertisements