Home > Software engineering >  Deleting multiple elements in a list - with a list of item locations
Deleting multiple elements in a list - with a list of item locations

Time:11-26

I have two lists.

List1 is the list of items I am trying to format

List2 is a list of item locations in List1 that I need to remove (condensing duplicates)

The issue seems to be that it first removes the first location (9) and then removes the second (16) after...instead of doing them simultaneously. After it removes 9, the list is changed and 16 is removed in a different intended location because of that.

List1 = ["HST", "BA", "CRM", "QQQ", "IYR", "TDG", "HD", "TDY", "UAL", "CRM", "XOM", "CCL", "LLY", "QCOM", "UPS", "MPW", "CCL", "ILMN", "MU", "GOOGL", "AXP", "IVZ", "WY"]
List2 = [9, 16]

print(List1)
print(List2)


for x in List2:
    List1.pop(x)

print(List1)

CodePudding user response:

You can sort List2 and reverse it afterward (sorted(List2, key=List2.index, reverse=True)). Then python will remove these elements from back to the front:

List1 = ["HST", "BA", "CRM", "QQQ", "IYR", "TDG", "HD", "TDY", "UAL", "CRM", "XOM", "CCL", "LLY", "QCOM", "UPS", "MPW", "CCL", "ILMN", "MU", "GOOGL", "AXP", "IVZ", "WY"]
List2 = [9, 16]

List2 = sorted(List2, key=List2.index, reverse=True)
for x in List2:
    List1.pop(x)

print(List1)

CodePudding user response:

try with something like that

List1 = ["HST", "BA", "CRM", "QQQ", "IYR", "TDG", "HD", "TDY", "UAL", "CRM", "XOM", "CCL", "LLY", "QCOM", "UPS", "MPW", "CCL", "ILMN", "MU", "GOOGL", "AXP", "IVZ", "WY"]
List2 = [9, 16]

print(List1)
print(List2)


for i, x in enumerate(List2):
    List1.pop(x-i)

print(List1)

CodePudding user response:

Use:

S = set(List2)

out = [x for i, x in enumerate(List1) if i not in S]

CodePudding user response:

You can use enumerate to keep count of how many items you have removed and find their new location on the list.

If you remove one item, the index of the next item to be removed is -1.

for i, j in enumerate(list2):
    list1.pop(i - j)

the enumerate return a tuple with the value of the list and a count of the loop.

  • Related