0

I am trying to count the number of times a value shows up in a sorted list. I know I can just use the count method but why does the following code not work?

lst = []
a = ['polka dot sock\n', 'polka dot sock\n', 'polka dot sock\n', 'red sock\n', 'superhero shirt\n', 'torn jeans\n', 'white shirt\n', 'white shirt\n']
for x in a:
     c = 0
     while x in a:
          c += 1
          a.remove(x)
     lst.append((a, c)) 
print lst 

The code works for everything except 'red sock\n' and 'torn jeans\n'. Why is that? Is it an indexing issue?

green frog
  • 156
  • 1
  • 8

1 Answers1

0

TL;DR:

Yes, this is an indexing issue. The for loop continues to increment, and is applied over the modified list.

Long:

If you add:

    print x
    print a

after your a declaration, you get the following output:

    ['polka dot sock\n', 'polka dot sock\n', 'polka dot sock\n', 'red sock\n', 'superhero shirt\n', 'torn jeans\n', 'white shirt\n', 'white shirt\n']
    polka dot sock

    ['red sock\n', 'superhero shirt\n', 'torn jeans\n', 'white shirt\n', 'white shirt\n']
    superhero shirt

    ['red sock\n', 'torn jeans\n', 'white shirt\n', 'white shirt\n']
    white shirt

You can see that polka dot sock is a[0] of the original list, superhero shirt is a[1] of the modified list, and white shirt is a[2] of the again modified list. Due to this, your 'red shirt' and 'torn jeans' are getting skipped, since they're now a[0] and a[1] of your modified lists.

Community
  • 1
  • 1
Cody Schindler
  • 131
  • 1
  • 5