D
D
DTHRT2020-05-12 02:00:57
Python
DTHRT, 2020-05-12 02:00:57

What's wrong with the For loop in Python?

Hello!
I'm just starting to learn Python and started parsing lists. Everything seemed to be clear, until one moment.

There is a task:
Make a program that would remove duplicate numbers from the list.

Solution:
I started solving the problem with a For loop, code:

numbers = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5] #список с нарочными дублями
item_2 = 0

for item in numbers: 
    if item_2 == item:
        print(item) #это я так дебажу
        numbers.remove(item)
    else:
        item_2 = item
print(numbers)


At the output I get: [1, 2, 2 , 3, 4, 4 , 5]
2 and 4 were not cut out, although the if condition itself successfully fulfills (If I remove numbers.remove (item) and just put some print() , then I will have exactly the same number of print() as duplicates, that is, it correctly finds everything)

However, if I change the code and do this:
numbers = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
# удалил отсюда item_2 = 0

for item in numbers:
    item_2 = numbers[item] #добавил эту строку
    if item_2 == item:
        print(item)
        numbers.remove(item)
    else:
        item_2 = item #item_2 = 2
print(numbers)


That all works great. My brain just explodes already, why didn't the first method work? As I understand numbers.remove(item) does not work. Although I already solved the problem, I did not understand the essence.
Please explain, I will be very grateful!)
Thank you all!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-05-12
@DTHRT

In general, it is better to remove duplicates from the list in this way

def main():
    numbers = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
    numbers = [number for number in set(numbers)]
    print(numbers)

if __name__ == '__main__':
    main()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question