Editor

Fix the Mutable Default

Intermediate · Fix the bug · from 15 Python Pitfalls That Trip Up Even Experienced Developers

From the lesson: 15 Python Pitfalls That Trip Up Even Experienced Developers

Python is famous for being readable and beginner-friendly. But lurking beneath that clean syntax are several traps that catch even experienced developers. These aren't bugs in Python - they're features that behave differently than you'd expect.

Read the lesson

The create_group function is supposed to create independent groups, but all groups share the same member list. Fix the bug so each call creates a fresh list.

After the fix, the code should print two independent groups.

def create_group(name, members=[]):
members.append(name)
return {'group': name, 'members': members}
team_a = create_group('Alice')
team_b = create_group('Bob')
print(team_a['members'])
print(team_b['members'])

More Common Pitfalls exercises

All Python exercises · 50 practice problems · Advanced Python quiz