In the following two examples, I am trying to remove negative element from a list using two different types of looping.
First I tried by using normal looping for i in list
but in this case when i do list1.remove(elm)
the size of the list is reduce by one element. So, in the next loop the second element moves to the first element position. So, the second element is missed from testing if elm < 0
in the next loop. So, it doesn't remove all the negative element from the list.
Secondly, I tried using slicing. What i understood from slicing is it creates a temporary list. So, when i do for i in list2[:]
it creates a new temporary list2 = [-1,3,-2,-5,4,7,8]
but still I didn't get a clear picture, how it works. It removes all the negative element.
#!/usr/env/bin
# remove all the negative value from the list.
list1 = [-1,3,-2,-5,4,7,8]
list2 = [-1,3,-2,-5,4,7,8]
# Looping through the list.
for elm in list1:
if elm < 0:
list1.remove(elm)
print 'list1: ', list1
# Looping through the list using slice.
for elm in list2[:]:
if elm < 0:
list2.remove(elm)
print 'list2: ', list2
Output:-python slice.py
list1: [3, -5, 4, 7, 8]
list2: [3, 4, 7, 8]