Jan 2, 2013

Python difference between list copy and reference


inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]

#The following Shares same memory location
inspiring_ppl_1 = inspiring_ppl

inspiring_ppl.append("Abdul Kalam")
inspiring_ppl_1.append("Abraham Lincoln")

#Therefore inspiring_ppl, inspiring_ppl_1 contains the same contents including "Abdul Kalam" and "Abraham Lincoln"

#Python does not have variables like C 
#In Python variables are just tags attached to objects

#The following shares different memory location
inspiring_ppl_2 = inspiring_ppl[:]

inspiring_ppl.append("Swami Vivekananda")

print(inspiring_ppl)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Abdul Kalam", "Abraham Lincoln"]

print(inspiring_ppl_1)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Abdul Kalam", "Abraham Lincoln"]


print(inspiring_ppl_2)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Swami Vivekananda"]

No comments:

Post a Comment