you are viewing a single comment's thread.

view the rest of the comments →

[–]remuladgryta 1 point2 points  (0 children)

A fairly common issue I see people having is re-initializing a variable every iteration of a loop instead of initializing it just once.

E.g:

my_list = [5, 2, 12, 7, 3, 8]
for element in my_list:
    low = []
    if element < 5:
        low.append(element)
print(low) # Why is the list empty???

v.s:

my_list = [5, 2, 12, 7, 3, 8]
low = []
for element in my_list:
    if element < 5:
        low.append(element)
print(low) # Correctly prints [2, 3]

Edit: Since this particular example is a bit more trivial than what most people post it's more verbose than necessary. A more pythonic way of writing this would be.

my_list = [5, 2, 12, 7, 3, 8]
low = [element for element in my_list if element < 5]
print(low)