Remove Tuples of Length K in Python


When it is required to remove the tuples of a specific length ‘K’, list comprehension can be used.

Below is the demonstration of the same −

Example

 Live Demo

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 ")
print(K)
my_result = [ele for ele in my_list if len(ele) != K]

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

Output

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

Explanation

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

  • The value of K is assigned and displayed on the console.

  • The list comprehension is used to check the length of every element in the list of tuple.

  • This is assigned to a variable

  • It is displayed as output on the console.

Updated on: 17-Apr-2021

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements