Safe List Filtering
Intermediate · Write the code · 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 lessonWrite a function remove_negatives(numbers) that returns a new list with all negative numbers removed. Do NOT modify the original list.
Test with nums = [3, -1, 4, -5, 2, -3, 6]. Print the result of remove_negatives(nums) and then print nums to prove it's unchanged.
# Write remove_negatives that returns a new list
# without negative numbers (don't modify the original)
nums = [3, -1, 4, -5, 2, -3, 6]
# Print the filtered result
# Print the original to prove it's unchanged
More Common Pitfalls exercises
- Fix the Mutable DefaultIntermediate
- Predict the Output: Late BindingIntermediate
- Fix the Bug: Shallow Copy SurpriseIntermediate
- Predict the Output: Variable ScopeIntermediate
- Safe Exception HandlingIntermediate
- Build a Safe Defaults FunctionIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz