0

Let's say I have a couple of functions which generate different results each time they're called. For the sake of this post only:

import random

def random_name():
    return random.choice(['Matthew', 'Mark', 'Luke', 'John'])

def random_city():
    return random.choice(['Chicago', 'Atlanta', 'New York', 'San Diego', 'Boston'])

I need to be able to create a list of n unique outputs from a given function f. I also need to be able to add additional unique outputs to an existing list (set) using the same function. I have:

def unique(func, length, s = set()):
    while len(s) < length:
        s.add(func())
    return list(s)

When I call it for the first time, the results are as expected:

unique(random_name, 2)
# ['John', 'Luke']

However, when I call it again and pass a different func, I get the following:

unique(random_city, 3)
# ['John', 'Luke', 'Chicago']

If I change my function as follows, it behaves as desired:

def unique(func, length, s = None):
    s = s if s is not None else set()

    while len(s) < length:
        s.add(func())
    return list(s)
unique(random_name, 2)
# ['John', 'Luke']

unique(random_city, 2)
# ['Boston', 'Atlanta']

Why does the set s persist when it is defined as an optional parameter s = set()?

0 Answers0