August 1, 2026
Python Trap
Recently I started to learn Python. Well I did have a beginner level understanding of the language earlier(somewhat). But this time I…
By S Wrights
2 min read
Recently I started to learn Python. Well I did have a beginner level understanding of the language earlier(somewhat). But this time I decided to get properly into the language's ecosystem. So as most of us homo sapiens, I took an online course and once the course was over, I was confident that I had the language at my fingertips. Consequently, I asked an AI assistant to give me quiz for a beginner to intermediatory level of expertise. I scored about 60%. Oh boy!!! I was expecting more. So yes the said assistant helped me successfully debunk my myth that I had mastered Python.
So after this I was determined to go down the rabbit hole of "Where it went wrong?" I found some, what I found out was, I had stepped on a few of Pythons' memory traps or bugs if you may call them so.
So, in my weekly story, today I have decided to deep dive into one of those traps. So without further ado, here it is.
This is the Pythons' Default Argument Trap.
So here is a snippet below, I would suggest, before you scroll down, please try to guess the answer.
If your output looks something like below:
Well Congratulations my friend!!! you got it absolutely wrong!! just the way I got it once upon a time. But fret not, I am here to the rescue.
The correct output is:
Let me help you out if you are as baffled as I was when I saw the result to a similar snippet. Before I explain the output, let me mention a couple of noteworthy points:
- List in Python is a mutable datatype
- Default arguments in Python are created just once at the time of function definition
So, now here is what happened :-
When the 1st function call was executed, the my_list at that time was referencing to an empty list. During the the call, my_list was appended and now the empty list had an element i.e [1000].
When the 2nd time call was executed, since my_list was created at the time of function definition, hence it kept referencing the same list which now contained [1000]. So when append was called, the list now had 2 elements in it → [1000,1002].
The point I would like to stress on is, the same list reference: my_list, kept pointing to the same list in the memory. Just each time after the function call the elements were added to the same list.
Now, in case you want a new list every time the function is called, we use "None" to initialize the reference variable: my_list at the time of function definition and create a list inside the function. This way a fresh list gets created for every function call.
So this was a trap which is now debunked successfully for a lot of Python noobs out there!!!
Please do let me know if you came across any other traps or bugs. We can explore further down those mini rabbit holes as well!!