Telegram Group & Telegram Channel
🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.



tg-me.com/pro_python_code/1804
Create:
Last Update:

🐍 Python-задача с подвохом: “Список-призрак”

📘 Условие

Посмотри на этот код:


def append_item(item, lst=[]):
lst.append(item)
return lst

result1 = append_item(1)
result2 = append_item(2)
result3 = append_item(3)

print(result1)
print(result2)
print(result3)


Вопрос:
Что выведет программа и почему?

🔍 Варианты ответа:

А)

[1]
[2]
[3]


Б)

[1]
[1, 2]
[1, 2, 3]


В)

[3]
[3]
[3]


Правильный ответ: Б

Почему?

💥 Подвох: аргумент lst=[] — мутабельный объект, и он создаётся только один раз при определении функции, а не при каждом вызове.

📌 То есть каждый вызов append_item модифицирует один и тот же список, который "помнит" все предыдущие элементы.

Как исправить:


def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst


Теперь каждый вызов создаёт новый список, если его не передали явно.

⚠️ Подвох

• Аргументы по умолчанию вычисляются один раз
• Это работает и с dict, и с set, и с любыми объектами
• Даже опытные Python-разработчики иногда "попадаются" на этом

🎯 Отлично подходит для проверки глубокого понимания поведения функций в Python.

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1804

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

Telegram Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

Look for Channels Online

You guessed it – the internet is your friend. A good place to start looking for Telegram channels is Reddit. This is one of the biggest sites on the internet, with millions of communities, including those from Telegram.Then, you can search one of the many dedicated websites for Telegram channel searching. One of them is telegram-group.com. This website has many categories and a really simple user interface. Another great site is telegram channels.me. It has even more channels than the previous one, and an even better user experience.These are just some of the many available websites. You can look them up online if you’re not satisfied with these two. All of these sites list only public channels. If you want to join a private channel, you’ll have to ask one of its members to invite you.

Python RU from ca


Telegram Python RU
FROM USA