Python | Remove a tuple from a list of tuples if it contains no characters

Python Methods and Functions | Regular Expressions

Example :

  Input:  [(',', 12), ('...', 55), ('- Geek', 115), ('Geeksfor', 115),]  Output:  [(' -Geek', 115), ('Geeksfor', 115)] 

Method # 1: Using List Comprehension

# Python code to remove all of these
# items from a list of tuples
# which does not contain an alphabet.

  
# Initialization list

List = [( ', ' , 12 ), ( 'Paras' , 5 ),

  ( ' jain.' , 11 ), ( '...' , 55 ) ,

( '-Geek' , 115 ), ( ' Geeksfor' , 115 ),

( ':' , 63 ), ( 'Data' , 3 ), ( ' -' , 15 ),

( 'Structure' , 32 ), ( 'Algo' , 80 ),]

 
# Using the comprehension list

out = [(a, b) for a , b in List  

if any (c.isalpha () for c in a)]

  
# Printout

print (out)

Exit:

[('Paras', 5), ('jain.', 11), ('-Geek', 115), ('Geeksfor', 115), ('Data', 3), ('Structure', 32), ('Algo', 80)]

Method # 2: Using Regex

# Python code to remove all these
# elements from the list of tuples
# which does not contain an alphabet.

 
# Initialization list

List = [( ',' , 12 ), ( 'Paras' , 5 ),

  ( 'jain.' , 11 ), ( '...' , 55 ),

( '-Geek ' , 115 ), ( 'Geeksfor' , 115 ),

( ':' , 63 ), ( ' Data' , 3 ), ( '-' , 15 ),

( 'Structure' , 32 ), ( ' Algo' , 80 ),]

 
# Import

import re

 
# Using regular expressions

out = [t for t in List if re.search (r ' w' , t [ 0 ])]

 
# Printout

print (out)

Exit :

[('Paras', 5), ('jain.', 11), ('-Geek', 115), ('Geeksfor', 115), ('Data', 3), ('Structure', 32), ('Algo', 80)]


Method 3: Using Filter and Lambda

# Python code to remove all of these
#ele cops from a list of tuples
# which does not contain an alphabet.

 
# Initialization list

List = [( ',' , 12 ), ( ' Paras' , 5 ),

( 'jain.' , 11 ), ( '...' , 55 ),

( ' -Geek' 115 ), ( 'Geeksfor' , 115 ),

( ': ' , 63 ), ( 'Data' , 3 ), ( '-' , 15 ),

( ' Structure' , 32 ), ( 'Algo' , 80 ),]

  
# Using the filter

out = filter ( lambda x: any (c.isalpha ()

  for c in x [ 0 ]), List )

 
# Convert to list

out = list (out)

 
# Output print

print (out)

Exit:

[('Paras', 5), ('jain.', 11), ('-Geek', 115), ('Geeksfor' , 115), ('Data', 3), ('Structure', 32), ('Algo', 80)]





Get Solution for free from DataCamp guru