Search code examples
pythonlistfor-loopif-statementnonetype

How can I remove None values of one list and the equivalent values from another?


I have been trying to solve this problem for a while. What I am trying to do is remove the None values from a list like:

list1 = [2,3,4,None,2,4,5]

I also have other lists that have correlated values to the list1 values (imagine list1 is days and the other two are things that happen in those lists):

list1 = [2,3,4,None,2,4,5]

list2 = ['red','blue','white','red','blue','blue','blue']

I want to remove the None value and also the red from the other list. So I want them to look like:

list1 = [2,3,4,2,4,5]

list2 = ['red','blue','white','blue','blue','blue']

What I have tried is the following:

    for j in array_length(list1):
        
        if list1[j] is None: #if value is None
            print("Missing values. Omitting day.")
            del list1[j] #deleting that day from all datasets
            del list2[j]
            

Where array_length is a function I have created to give me an array from 0 to the lenght of the list I am targetting. The above code does not work, as it gives me the following error:

IndexError: list index out of range

What I think is happening is that the indexes are not updating correctly, but I dont know how to solve it or get around it.


Solution

  • The problem is caused because you're deleting items from the list while looping. So when you start the loop the length of the list was 7, but because you deleted one item in the middle, the loop goes out of index in the final stage. Lesson: Don't delete from list while using it in a loop.

    But here is a way to do it without causing error

    list1 = [2,3,4,None,2,4,5]
    list2 = ['red','blue','white','red','blue','blue','blue']
    
    for i, val in enumerate(list1):
      if val is None:
        del list1[i]
        del list2[i]