-1

I need a sanity check. The top1 and top2 functions are nearly the same but output very different contents for the freq variable. Why? What am I not seeing?

def top1(nums, k):
    count = {}
    
    for i in nums:
        if i not in count:
            count[i] = 1
        else:
            count[i] += 1
    
    freq = (len(nums) + 1) * [[]]

    print('count', count)
    print('freq', freq)
    for n, c in count.items():
        freq[c].append(n)
    print('freq', freq)


def top2(nums, k):
    count = {}

    for n in nums:
        count[n] = 1 + count.get(n, 0)

    freq = [[] for i in range(len(nums) + 1)]

    print('count', count)
    print('freq', freq)
    for n, c in count.items():
        freq[c].append(n)
    print('freq', freq)

top1([1], 1)
print()
top2([1], 1)

OUTPUT

count {1: 1}
freq [[], []]
freq [[1], [1]]

count {1: 1}
freq [[], []]
freq [[], [1]]
croatoan
  • 31
  • 4

1 Answers1

1
freq = (len(nums) + 1) * [[]]

multiplies a list to create a list of multiple references to the same list. Mutating one entry in the outer list affects all of the other entries, because each entry is a reference to a single shared list object.

freq = [[] for i in range(len(nums) + 1)]

is a list comprehension that creates a list of multiple distinct lists. Mutating one entry in the outer list does not affect the other inner lists.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • This is it. Thank you! I'll accept your answer as soon as I can cause StackOverflow says I have to wait 11 minutes to do so. – croatoan Sep 05 '22 at 15:00