zingy
zingy

Reputation: 811

dealing with an empty list inside a list

I have a list which looks something like this:

mylist = ([(0.1, 0.5),(0.4, 1.0)], [(0.2, 0.4),(0.15, 0.6)], None, [(0.35, 0.8),(0.05, 1.0)]) 

What I would like to know is how do I check for the empty entry or None in the list and if there is one then it should continue further ignoring it. Something like,

if mylist == something :
    do this

if mylist == [] or () or None :
    ignore and continue      

I am not able to put that into a code. Thank you.

Upvotes: 2

Views: 10273

Answers (4)

agf
agf

Reputation: 176950

for sublist in mylist:
    if sublist is None:
        #what to do with None
        continue
    elif not sublist and isinstance(sublist, list):
        #what to do if it's an empty list
        continue
    elif not isinstance(sublist, list):
        #what to do if it's not a list
        continue
    #what to do if it's a list and not empty

Alternatively, you could leave out the 'continues' and put the general case in an else clause, only check for some of the possible circumstances, or nest the ifs.

Generally, if you knew you'd only get None or a container, just if not sublist: continue is adequate to ignore empty containers and None. To filter these values out of the list, do

mylist = [sublist for sublist in mylist if sublist]

Edit: You can't do this in the update function. You should pre-filter the list. Where you have

mylist = oldlist[:]

replace it with

mylist = [sublist for sublist in oldlist if sublist]

If the row name a, b, or whatever is there, but the rest is empty / None, then do

mylist = [sublist for sublist in oldlist if sublist[1]]

and this will filter on the truth value of the 2nd item intead of the first item / row title.

Upvotes: 2

Hassek
Hassek

Reputation: 8995

I will just do this:

for x in mylist:
    if not x:
        continue

    #--> do what you want to do

but I have to say the first answer with comprehension list is more clean unless you need to do a complicated stuff inside the for statement.

Upvotes: 1

Shaokan
Shaokan

Reputation: 7684

Basically, in python

[], (), 0, "", None, False 

all of these means that the value is False

Therefore:

newList = [i for i in myList if i] # this will create a new list which does not have any empty item

emptyList = [i for i in myList if not i] # this will create a new list which has ONLY empty items

or as you asked:

for i in myList:
    if i: 
      # do whatever you want with your assigned values
    else:
      # do whatever you want with null values (i.e. [] or () or {} or None or False...)

and then you can do whatever you want with your new list :)

Upvotes: 4

Wizz
Wizz

Reputation: 1267

How about this piece of code:

for x in mylist:
     if x is None or x == [] or x == ():
             continue
     else:
             do this

Upvotes: 0

Related Questions