[Python] Dictionary inside/outside for loop

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to change one of my elements in the dictionary but if I were to put new_alien outside the loop, all the elements in the dictionary get changed. Why is that?

    #ALL aliens get changed when I put put the dictionary up here
    new_alien = {'colour': 'green'}

    aliens=[]

    for alien_number in range(3):
    #if i put new_alien here only one alien dictionary gets changed in the for loop (correct code)
    #new_alien = {'colour': 'green'}
    aliens.append(new_alien)

    print(aliens)

    for alien in aliens[0:1]:
    if (alien['colour'] == 'green'):
    alien['colour'] = 'yellow'

    print(aliens[0:2])


    Output if new_alien is outside the loop:

    [{'colour': 'green'}, {'colour': 'green'}, {'colour': 'green'}]
    [{'colour': 'yellow'}, {'colour': 'yellow'}]


    Output if new_alien is inside the loop:

    [{'colour': 'green'}, {'colour': 'green'}, {'colour': 'green'}]
    [{'colour': 'yellow'}, {'colour': 'green'}]


    Notice how outside the loop all alien dictionary:colour gets changed to yellow.

    Continue reading...

Compartilhe esta Página