Reputation: 728
Hello I have a loop which goes counts different records in my MySQL database and then saves the numbers to a list. Here is the list:
[1L, 2L, 2L, 5L, 4L, 1L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 1L, 2L, 4L, 2L, 1L, 3L, 1L, 2L, 4L, 1L, 2L, 1L, 1L, 3L, 1L, 3L, 1L, 5L, 2L, 1L, 1L, 5L, 1L, 1L, 1L, 4L, 2L, 1L, 3L, 2L, 1L, 2L, 2L, 2L, 3L, 1L, 1L, 3L, 2L, 2L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 3L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L]
now I go thru this list and I want to leave only single numbers (means 1L, 2L etc) I'm using this loop: for number in legend:
print number # to check what number it does currently
counter = legend.count(number)
while counter > 1:
legend.remove(number)
counter -= 1
then I see that it checks 1,2,3,4,3,2,1 ...why is that? why this loop wont check number 5? at the end the list looks like this:
[5L, 5L, 5L, 4L, 3L, 2L, 1L]
that means it works but why it doesn't go for number 5?
thx in advance
Upvotes: 0
Views: 333
Reputation: 1975
You might fall into problem such as:
list = [1,2,3,4]
for l in list:
print "Elem ", l
if l == 2:
list.remove(1)
which gives output:
Elem 1
Elem 2
Elem 4
List is modified in loop and while removing some element that you already looped through you are skipping one element in list.
Upvotes: 0
Reputation: 76838
Just put it in a set
.
>>> foo = [1,1,1,2,2,3,3,4,1,4,3,6,5,6]
>>> set(foo)
set([1, 2, 3, 4, 5, 6])
This will automatically filter out all duplicates. Maybe you can even skip the list, and put it in a set
in the first place.
Upvotes: 7