python-2.7loopsfor-loopfloating-pointcustom-lists

What to code to delete any item in a list that can not be converted into a float?


I am not sure what to write for a 'for loop' in order to delete any item in a list that is not an integer that can not be converted into a float, delete empty strings, and delete None types. Let's say my code is:

    list1=['10', '', 'pig', '45', '&', None, '30']    
    new_list1=[]
    for item in list1:    
    

So after my code is complete, it should give me:

    new_list1=[10.0,45.0,30.0]

What would I need to fill into my 'for loop' to get the integers from list1 into new_list1 as floating point numbers?


Solution

  • try:
      new_list1.append(float(item))
    except (ValueError, TypeError):
      pass