The Python Trap That Catches EVERY Beginner! #shorts
239views
1likes
00:46
T
Taught by Celeste AI - AI Coding Coach
View on YouTubeDescription
Can you guess what this Python code prints?
python:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
This is one of Python's most famous gotchas - the mutable default argument trap! Default mutable arguments like lists and dictionaries are created ONCE when the function is defined, not each time it's called. This means the same list is shared between all function calls!
The fix? Use None as the default and create a new list inside the function:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Follow @GoCelesteAI for more coding quizzes and programming tips!
#python #programming #coding #developer #programmer #tech #codingquiz #pythontips #learnpython #softwareengineering #codetest #interviewquestions #shorts
python, programming, coding, developer, programmer, tech, codingquiz, pythontips, learnpython, softwareengineering, codetest, interviewquestions, shorts, mutable default arguments, python gotchas, python bugs, python interview, coding challenge