Reputation: 304
Which of the following two codes are more efficient? (time & memory).
aList = [0,1,2,3,4,5,6,7,8,9]
for num in aList:
if (num % 2 == 0):
aList.pop(num)
or
aList = [0,1,2,3,4,5,6,7,8,9]
for num in range(10):
if (num % 2 == 0):
aList.pop(num)
So basiccaly what I'm asking is which of "for num in aList:" and "for num in range(10):" are more efficient ?
Upvotes: 0
Views: 56
Reputation: 304137
Even if your loop did work, pop
is O(n) so makes your loop very inefficient. It's nearly always better to make a new filtered list and copy that back over
aList = [0,1,2,3,4,5,6,7,8,9]
aList[:] = [n for n in aList if n % 2]
Upvotes: 1