Home > database >  Why [a,b] and a b have different values with APPEND command in My Paython Code?
Why [a,b] and a b have different values with APPEND command in My Paython Code?

Time:04-18

I am new in Python.. But i realy confused with this problem...

The Print Results of the last 3 lines :

['John', 'Philiph', 'Derek', 'Melanie', 'Romy', 'Andy', 44]

[1, 2, 3, 4, 5, 6, 'John', 'Philiph', 'Derek', 'Melanie', 'Romy', 'Andy']

[[1, 2, 3, 4, 5, 6], ['John', 'Philiph', 'Derek', 'Melanie', 'Romy', 'Andy', 44]]

**QUESTION : ** 44 is in the t BUT---> WHY 44 isn't in the x

CODE :

z=[1,2,3,4,5,6]
h=['John', 'Philiph', 'Derek', 'Melanie', 'Romy', 'Andy']
x=z h
t=[z,h]
#print(x)
#print(t)
h.append(44)
print(h)
print(x)
print(t)

CodePudding user response:

z h will create a single list containing h and z values meanwhile the [z,h] create a list of the two lists h and z

CodePudding user response:

t=[z,h]

This puts references to z and h into a list, and names that list t. No copies of data are made.

x=z h

This makes a new list that's a result of adding z and h, and saves that new list into x. Affecting h doesn't affect x because x doesn't contain the original h; it contains copies of references to the elements h held. Changes made to h can be seen in t though because t contains a reference to the original h.

  • Related