0

I understand that it is something simple but can't understand it

why is my variable 'a' modified?

a=["A","E"]
for x in range(0,2):
    b=a
    b.extend(["I","O","U"])   
    print(b)   
print(a)

Output:

b(first loop)=['A', 'E', 'I', 'O', 'U']
b(second loop)=['A', 'E', 'I', 'O', 'U', 'I', 'O', 'U']
a=['A', 'E', 'I', 'O', 'U', 'I', 'O', 'U']

My variable 'a' would have to be ["A","E"] at the end of the loop and each repetition 'b' would have to be ["A","E","I,"O","U"]

Fernando
  • 33
  • 1
  • 2

1 Answers1

1

Because both variables a and b reference the same object.

a = ["A","E"]
b = a

print(id(a))
print(id(b))
print(a is b)

output:

140387638915552
140387638915552
True
sarartur
  • 1,178
  • 1
  • 4
  • 13