Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Removing strings from tuple in Python



When it is required to remove the strings froma  tuple, the list comprehension and the 'type' method can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

The 'type' method returns the class of the iterable passed to it as an argument.

Below is a demonstration for the same −

Example

Live Demo

my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]

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

my_result = [tuple([j for j in i if type(j) != str])
   for i in my_list]
print("The list of tuple after removing the string is : ")
print(my_result)

Output

The list is :
[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
The list of tuple after removing the string is :
[(45, 67), (45, 32), (59, 13)]

Explanation

  • A list of tuple is defined, and is displayed on the console.
  • It is iterated over, using list comprehension.
  • It is checked to see for not being a string.
  • It is then converted to a tuple, and then to a list again.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.
Updated on: 2021-03-13T05:32:44+05:30

663 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements