The difference between PHP and Python in the assignment?

advertisements

I have learned PHP and now I'm learning Python. I have written this code in both languages, but its behaviour differs.

PHP:

<?php
        $x = [];
        $y = $x;
        $x['key'] = 'value';
        var_dump($x);
        var_dump($y);

Python:

    x = {}
    y = x
    x['key'] = 'value'
    print(x)
    print(y)

y is null in PHP , but not in Python.

I want to know why..


In PHP, when you’re assigning $y = $x, it copies the array. In Python, dictionaries are objects, and you merely copy the reference—not the dictionary itself. If you want to copy the dictionary, there’s a method for that:

x = {}
y = x.copy()
x['key'] = 'value'
print(x)
print(y)