Aware with the way Python treat and re-use existing objects


Python has a unique way when creating and re-using objects. See this example :

1
2
3
4
5
6
7
8
def x(y=[]):
    y.append("1")
    return y

if __name__ == "__main__":
    print x()
    print x()
    print x()

This will showing result:

1
2
3
[‘1’]
[‘1’, ‘1’]
[‘1’, ‘1’, ‘1’]

Why this is happen? See the logic behind. When the objects y which is not exists, Python will create this objects once the first x() executed. Then come to next of x() execution which Python interpreter will looking for the y and check whether it’s exists or not. If the objects exists, then Python will re-use it and we see the “[‘1’, ‘1’]” result on second execution.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.