0

I'm interested in understanding why lists and tuples behave differently using a recursive function that keeps track of what arguments have been used in a branch of a decision tree.

The function takes an integer as an input (a dictionary key) and an empty tuple. The key, its corresponding values and the empty tuple are printed. The integer is then 'added' to the tuple and the function is called on each of the values recursively, passing the tuple into used_keys.

data = {0:[1,2,3],1:[4],2:[4],3:[4]}

# 
def recursive(key, used_keys=()):
    print("used_keys: " + str(used_keys))
    print(key, data[key])
    used_keys += (key,)
    for k in data[key]:
        try:
            recursive(k, used_keys=used_keys)
        except KeyError:
            pass

if __name__ == '__main__':
    recursive(0)`

In this case, the result is as I expected. When the values [1,2,3] in the first key-value pair are looped over, the used_keys shows [0,1], [0,2] and [0,3]. However, when you replace the tuple with a list as shown below, the behavior changes:

def recursive(key, used_keys=[]):
    print("used_keys: " + str(used_keys))
    print(key, data[key])
    used_keys += [key]
    for k in data[key]:
        try:
            recursive(k, used_keys=used_keys)
        except KeyError:
            print("End")

In this case, all keys iterated in previous loops are retained in used_keys showing [0,1] for key 1, [0,1,2] for key 2 and [0,1,2,3] for key 3.

Thanks!

Iznogoud
  • 1
  • 1

0 Answers0