python/응용
자주하는 실수
wefree
2023. 5. 7. 21:03
How to remove elements in a Python List while looping
a = [1, 2, 2, 3, 4]
def even(x):
return x % 2 == 0
for item in a:
if even(item):
a.remove(item)
print(a)
결과: [1, 2, 3]
참고: https://www.python-engineer.com/posts/remove-elements-in-list-while-iterating/
Mutable Default Arguments
def append_to(e, to=[]):
to.append(e)
return to
my_list = append_to(12)
print(my_list)
my_other_list = append_to(42)
print(my_other_list)
출력결과
[12]
[12, 42]
Late Binding Closure
for multiplier in [lambda x: i * x for i in range(5)]:
print(multiplier(2))
출력결과
8
8
8
8
8
Global Variable
x = 3
def f():
y = x + 1
x = 2
f()
결과
UnboundLocalError: local variable 'x' referenced before assignment
참고: https://python-guide-kr.readthedocs.io/ko/latest/writing/gotchas.html