Загрузка...

The Python Trap That Catches EVERY Beginner! #shorts

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

Видео The Python Trap That Catches EVERY Beginner! #shorts канала Taught by Celeste AI - AI Coding Coach
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять