# Python; Question about the append (modifying lists): why modifying a list with append changes others? [closed]

I have a list named dict_eg1 whose values are lists.

dict_eg1 ={
"A":[1,2,3],
"B":[11,22,33],}
val1=dict_eg1["A"]
val1.append (100)#modify the list by using append.
print (dict_eg1)


{'A': [1, 2, 3, 100], 'B': [11, 22, 33]}

In this case, dict_eg1 changed.

However,

dict_eg1 ={
"A":[1,2,3],
"B":[11,22,33],}
val1=dict_eg1["A"]
val1 = [1, 2, 3, 100]#modify the list without using append.
dict_eg1


{'A': [1, 2, 3], 'B': [11, 22, 33]} In this case, dict_eg1 did not change.

Can anyone tell me why these two results were different??

• I’m voting to close this question because it is a pure python question and not related to bioinformatics. May 18 at 9:06
• To sum up, .append() modifies the list in-place, while assignment with = creates a new list entirely May 18 at 18:36

Welcome to Bioinformatics.

First of all, it should not be asked in this community since it is purely a question about python programming. I suggest that next time, please head to StackOverflow as you will likely receive more help from there.

You also look new to programming. This is more of a logical question. Let's break it up to understand what is happening in your first example:

# you define your dictionary containing two keys along with their values.
dict_eg1 = {
"A":[1,2,3],    # Key 'A' with a value as a list [1,2,3]
"B":[11,22,33]  # Key 'B' with a value as a list [11,22,33]
}

# you now define a new variable 'val1' which is
# the value of key 'A' and that is the list [1,2,3]
val1=dict_eg1["A"]

# as you have mentioned, doing the below command
# will append the value to the list of key 'A'
# in other words, you can also write it like so
# dict_eg1["A"].append(100)
# that's why when you make a change to 'val1'
# the value of the key 'A' of 'dict_eg1' will change
val1.append (100)


As for the second example (I will skip the same steps):

# ...

# you store the value of key 'A' in 'val1'
val1=dict_eg1["A"]

# however, in the below command, you actually
# !redefine! the value of 'val1' to a new list
# that is totally independent of your 'dict_eg1'
# In this case, 'dict_eg1' is not affected by
# any changes made to 'val1'
val1 = [1, 2, 3, 100]


Just to sum it up, when you use val1=dict_eg1["A"], imagine that you link the value of your key A to val1 and any changes made to val1 will affect dict_eg1["A"]. However, redefining val1 will disconnect that link.

• Thank you. I am sorry that I posted this question in the inappropriate community. May 19 at 2:46