1

I am trying to make a list of lists of about 5000 lists and it keeps messing up.
right now I just do this:

array = [[]]*5000
for line in f2:
    a = line.split()
    grid = int(a[0])
    array[grid].append(a[1])

print Counter(array[0]).most_common(10)

the problem is when I make the counter it does it as if the whole array of lists was actually just one list. Is there something obvious that I am doing wrong? Thanks

Alex Brashear
  • 864
  • 3
  • 9
  • 15

1 Answers1

7

Using [[]]*5000, you are creating 5000 reference to the same list in your outer list. So, if you modify any list, it will modify all of them.

You can get different lists like this:

a = [[] for _ in xrange(5000)]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • This answer is a duplicate to about 1000 other Python questions where the list of lists is initialized this way. I think we need "Frequently Answered Answers", and then we can just say "See FAA #27" or whatever. Other candidates: "Syntax error on line N means unmatched parentheses on line N-1", "Comparing 1 < '0' will not give the result you think it will, because they are different types". Hm, I think I'll post a new Community Wiki question... – PaulMcG Jul 01 '13 at 19:32