Home > Blockchain >  Removing elements from a list using indexs from another
Removing elements from a list using indexs from another

Time:12-19

I have written a function that collects all index positions of 'NULL' and 'NaN' strings that appear in a list and append them to another list called num. I am now trying to write a function that goes through the list that holds the strings 'NULL' and 'NaN' and uses the index positions from the num list to remove them.

I have coded these so far without success.

l = ['NULL', 32, 43, 'NaN', 45, 89, 11, 'NULL']
num = [0, 3, 7]

def rowRemover():
    for i in num:
        l.pop(num[i])

rowRemover()
print(l)


def rowRemover():
    i = 0
    while i < len(num):
        l.pop(num[i])
        i  = 1

rowRemover()
print(l)

I would appreciate your help. Thanks

CodePudding user response:

Instead of popping elements from a list, consider a list comprehension. Since we'll be checking if indices match and checking if an item exists in a set is cheaper than doing the same with a list, convert num to num_set. Then enumerate function will help you identify which elements to exclude:

l = ['NULL', 32, 43, 'NaN', 45, 89, 11, 'NULL']
num_set = set([0, 3, 7])

new_l = [x for i, x in enumerate(l) if i not in num_set]

Output:

[32, 43, 45, 89, 11]
  • Related