Even if you think you know pass by reference and pass by value, truth be told, you get thrown off sometimes. Recently, I was solving a graph problem, and I was stuck for a few hours because of this. Let me explain.
To simplify the problem, essentially I need to create an array with n arbitrary None values. Note, python None is like null in other languages. After which I have to loop over another array with tuples in them to extract indices from the tuples. Sounds confusing? Let me illustrate.
In this case, I can either create [[None],[None]…] array or [None,None…] array. The logic seems to work for either way.
Initially, I chose the [[None],[None]…], here is what I did
lst = [(100, 1, 2), (101, 1, 3), (102, 1, 4), (103, 3, 4)]adj_lst = [[None]]*(4)for triple in lst: if adj_lst[triple[1]][0] == None: adj_lst[triple[1]][0] = [(triple[2],triple[0])] else: adj_lst[triple[1]].append((triple[2],triple[0]))
But the output is simply just wrong. I was stuck at this for so long till i used python tutor to visualize
As you can see, the adj_list is simply pointing to a single None object. If you modify the None, everything changes after that.
Hence, in this case, a simple, [None]*n would be better. We can see the code here
adj_lst = [None]*(n)lst = [(100, 1, 2), (101, 1, 3), (102, 1, 4), (103, 3, 4)]for triple in lst: if adj_lst[triple[1]] == None: adj_lst[triple[1]] = [(triple[2],triple[0])] else: adj_lst[triple[1]].append((triple[2],triple[0]))
I hope my hours wasted can help you save some time :)