How to remove empty tuples from a list with python

Configurare noua (How To)

Situatie

We will see how can we remove an empty tuple from a given list of tuples.

Backup

Example:

Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), 
                  ('krishna', 'akbar', '45'), ('',''),()]
Output : [('ram', '15', '8'), ('laxman', 'sita'), 
          ('krishna', 'akbar', '45'), ('', '')]

Input : tuples = [('','','8'), (), ('0', '00', '000'), 
                 ('birbal', '', '45'), (''), (),  ('',''),()]
Output : [('', '', '8'), ('0', '00', '000'), ('birbal', '', 
          '45'), ('', '')]

Solutie

Pasi de urmat
def Remove(tuples):
    tuples = [t for t in tuples if t]
    return tuples
 
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), 
          ('krishna', 'akbar', '45'), ('',''),()]
print(Remove(tuples))

Output:

[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 
                           'akbar', '45'), ('', '')]

Method2:

Using the inbuilt method filter() :

def Remove(tuples):
    tuples = filter(None, tuples)
    return tuples
 
# Driver Code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), 
          ('krishna', 'akbar', '45'), ('',''),()]
print Remove(tuples)

Output:

[('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar','45'), ('', '')]

Tip solutie

Permanent

Voteaza

(8 din 19 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?