[Python] Why does creating a list inside or outside the for loop produce different results?

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I'm creating a program that removes duplicate numbers from a list. The point of the exercise is to use "not in" and "in" operators.

    The first time I created the code I created the list without the duplicates inside my for loop. I got a strange answer but I knew the code was correct. Moving the list creation outside the for loop produced the correct result and I dont understand why

    Correct output:

    my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]

    new_list = []
    for i in my_list:
    if i not in new_list:
    new_list.append(i)

    print("The list with unique elements only:")
    print(new_list)


    Incorrect output:

    my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]

    for i in my_list:
    new_list = []
    if i not in new_list:
    new_list.append(i)

    print("The list with unique elements only:")
    print(new_list)


    My second code didn't work, it just produced the number 9 but my first piece of code (after moving the list creation statement outside the for loop) gave me the correct result.

    Continue reading...

Compartilhe esta Página