Search code examples
pythonlistside-effects

Why this python code occurs the side-effect?


def to_un(g):
    un = []
    for v in g:
        un.append(v)
    print(g)
    for v in range(len(un)):
        for u in un[v]:
            if v not in un[u]:
                un[u].append(v)
    print(g)
    print(g == un)
    print(g is un)

def main():
    a = [[1], []]
    to_un(a)


if __name__ == "__main__":
    main()

result:

[[1], []]
[[1], [0]]
True
False

I expected that the value of g should not changed but it actually changed. I don't know what side-effect was occurred in this code.


Solution

  • un is a shallow copy of g, so the nested lists are references to the same lists in both. You need to copy the nested lists as well.

    un = [v[:] for v in g]