Search code examples
pythonlistindexingdel

How to remove several elements of a list by the index which can be changed each time?


I have a list like below:

A =  [1, 2, 3, 4]

After using enumerate I have the following list:

A = [(0, 1), (1, 2), (2, 3), (3, 4)]

After checking a condition, I realized that I don't need the elements with index 0 and 2. It means that my condition returns a list like below which can be different each time:

condA = [(0, 1), (2, 3)]

I know that I can use del or .pop() to remove an element from a list. However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list. I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

A_reduced = [2, 4]


Solution

  • If you want to read the index from the condA list and create the list of that number, the list of indices of elements to be removed will be like:

    rm_lst = [x[0] for x in condA]
    

    Now, to remove the elements from your main list:

    A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
    A_reduced = [x[1] for x in A if x[0] not in rm_lst]
    

    Final Code:

    A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))] 
    condA = [(0, ((11), (452))), (2, ((545), (757)))]
    rm_lst = [x[0] for x in condA]
    A_reduced = [x[1] for x in A if x[0] not in rm_lst]
    print(A_reduced)