𝗧𝗵𝗲 𝗣𝘆𝘁𝗵𝗼𝗻 "𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲" 𝗧𝗿𝗮𝗽 I noticed something interesting today : changed a value inside a function, and it reflected outside too I didn’t return anything. I didn’t re-assign the variable ➡️ 𝗧𝗵𝗲 𝗖𝗮𝘁𝗰𝗵 : Python functions don't always create a new "𝗰𝗼𝗽𝘆" of your data Instead, they often work with 𝗮 𝗿𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 to the original object ▪️𝗠𝘂𝘁𝗮𝗯𝗹𝗲 𝗼𝗯𝗷𝗲𝗰𝘁𝘀 (Lists, Dicts, Sets) are modified in place. Any change inside the function affects the original data directly. ▪️𝗜𝗺𝗺𝘂𝘁𝗮𝗯𝗹𝗲 𝗼𝗯𝗷𝗲𝗰𝘁𝘀 (Integers, Strings,Tuples) are safe because they can't be changed in place. ➡️ 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 : If you’re working with Lists or Dictionaries and want to keep your original data safe, you must be explicit: update(my_list.copy()) Small detail, but missing it can lead to hours of debugging bugs #Python #30DaysOfCode #SoftwareEngineering #LearningInPublic #Day19
You were passing a mutable object, as you said, so it's implicit that changing inside a function affects the content outside too. I don't get your concern, and disagree with your black and white do copy suggestion. If you're developing the solution, you know what you need, what you're don't hence how to treat the data. My little two cents
[70,80,90,100]
🙌
In fact, Python _always_ use references to objects. There is no variable, these are all names for objects in memory. When they are immutable, the object classes just don‘t implement mutation, instead it creates a new object: >>> a=5 >>> id(a) 5241202192 >>> a+=3 >>> id(a) 5241202288 >>> This is a core principle of Python. Understanding it makes it more clear.