0

I try to use 'uga' as input(=text). I want to get [['U','g','a'],['u','G','a'],['u','g','A'] as output.

I have tried this code :

text = 'uga'
abc = list(text)
out_list = []

for i in range (len(text)):
    out_list.append(abc)

x = out_list.copy()

for item in range(len(x)):
    x[item][item] = x[item][item].upper()
print(x)

after using that code I got [['U', 'G', 'A'], ['U', 'G', 'A'], ['U', 'G', 'A']] as the output.

If we cut the code...

text = 'uga'
abc = list(text)
out_list = []

for i in range (len(text)):
    out_list.append(abc)

x = out_list.copy()
print(x)

it will give [['u', 'g', 'a'], ['u', 'g', 'a'], ['u', 'g', 'a']] as the output.

after that I try to make the code without append(). I just make a new variable using this list --> [['u', 'g', 'a'], ['u', 'g', 'a'], ['u', 'g', 'a']] which is same as x

a = [['u', 'g', 'a'], ['u', 'g', 'a'], ['u', 'g', 'a']]
for item in range(len(a)):
    a[item][item] = a[item][item].upper()
print(a)

surprisingly I can get result which is [['U', 'g', 'a'], ['u', 'G', 'a'], ['u', 'g', 'A']]

after that I try again using append but manually, like this:

b = []
b.append(['u','g','a'])
b.append(['u','g','a'])
b.append(['u','g','a'])

for i in range (len(b)):
    b[i][i] = b[i][i].upper()

print(b)

the result is right too which is [['U', 'g', 'a'], ['u', 'G', 'a'], ['u', 'g', 'A']]


I don't know why my first code give the wrong result... because when I check the type of x , a, and b it same which is a list. After that I check a==b==x it gives the result True

I also put them in the same code which is:

for i in range (len(something)):
    something[i][i] = something[i][i].upper()

I have thinking a lot and ask many of friends, but no body could know what happened..

I'm sorry because my English is not very good. Hope you could help me...

Thank you

  • 2
    In the first snippet, `out_list[0] is out_list[1]`. In the second, it is merely the case that `out_list[0] == out_list[1]`. See [Is there a difference between “==” and “is”?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is). You need to copy `abc` so you have different sublists, not copy `out_list` (or use deepcopy). Check how your code runs in the visualizer [here](http://www.pythontutor.com/visualize.html#mode=edit) by stepping through it, and it should be abundantly clear. (Not writing an answer, because it will almost certainly be closed as a duplicate.) – Amadan Feb 10 '20 at 10:49

1 Answers1

0

You can see what happens if you add a print statement in the second loop. The output the looks like this:

[['U', 'g', 'a'], ['U', 'g', 'a'], ['U', 'g', 'a']]
[['U', 'G', 'a'], ['U', 'G', 'a'], ['U', 'G', 'a']]
[['U', 'G', 'A'], ['U', 'G', 'A'], ['U', 'G', 'A']]
[['U', 'G', 'A'], ['U', 'G', 'A'], ['U', 'G', 'A']]

As you can see the values all change at the same time. That happens because you add the abc object to the array 3 times and don't copy it.

Jina Jita
  • 136
  • 1
  • 3