Reputation: 155
I have a list
list=[[5,7,8],[2,8,4],[1,72,7],[8,79,80],[4,39,84],[6,78,89],[80,78,81],[12,39,50]]
and I have a list for indexes:
indexes=[1,3,7]
In the end, I want to remove 1st, 3rd and 7th element from the list
and the output should be like:
[[5,7,8],[1,72,7],[4,39,84],[6,78,89],[80,78,81]]
I used this code:
for i in indexes:
list.pop(i)
but it does not work, how can I fix that?
Upvotes: 1
Views: 1595
Reputation: 16
list=[[5,7,8],[2,8,4],[1,72,7],[8,79,80],[4,39,84],[6,78,89],[80,78,81],[12,39,50]]
indexes=[1,3,7]
for i in indexes[::-1]:
list.pop(i)
print(list)
Upvotes: 0
Reputation: 1
the code that you're looking for is this
my_list=[[5,7,8],[2,8,4],[1,72,7],[8,79,80],[4,39,84],[6,78,89],[80,78,81],[12,39,50]]
indexes=[1,3,7]
for i in indexes[::-1]:
my_list.pop(i)
print(my_list)
Rename the variable from "list" to something else since list is a reserved word. you'll also have to do this in the for loop.
because you want to pop items out of a list it's important you think about the order you do it in. So if you pop from position 1 then that means position 2 will now become position 1. this probably isn't what you want.
so it's important to pop from the end of the list first and work your way to the front if possible which is why I used the
indexes[::-1]
this is called list slicing you can learn more about it here. https://www.youtube.com/watch?v=ajrtAuDg3yw
Upvotes: 0
Reputation: 86
Your way of doing this won't work since you will mess up the original list indexes by working with a non-reversed list for the loop.
Given your values, you should sort the indexes list and reverse the order to not mess with the list index, I'm also using del to avoid useless returns from the pop method.
list=[ [5,7,8],[2,8,4],[1,72,7],[8,79,80],[4,39,84],[6,78,89],[80,78,81],[12,39,50] ]
indexes=[1,3,7]
for index in sorted(indexes, reverse=True):
del list[index]
Upvotes: 1
Reputation: 23770
Assuming the problem is caused by the mutation of the list during items popping:
for i in sorted(indexes, reverse=True):
list.pop(i)
The change in the code pops the items from the end first, so the indices of the other items is not affected.
Upvotes: 2
Reputation: 311393
I'd create a new list that doesn't include these indexes. Using a list comprehension over the enumerate
of the original list (so you can get the list and the index easily) can even make this a one liner:
result = [e[1] for e in enumerate(lst) if e[0] not in indexes]
Upvotes: 3