Overwriting variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Overwriting variables

So you can change the value of a variable without using del?

16th Aug 2019, 3:45 PM
Sam Hatchard
Sam Hatchard - avatar
3 Answers
+ 5
del doesn't necessarily free the memory. First of all it erases a NAME. a = [] # We create a list b = a # We give it a second name Now we can use the same list by calling it a or b in our code. del a now deletes the name a, but not the list. It's still there, in the same place, and you can still use it with the name b. del b Now the second name is also erased. And now, since nothing refers to b anymore, the garbage collector of Python deletes the actual object for you.
16th Aug 2019, 4:16 PM
HonFu
HonFu - avatar
+ 3
Whoops - the other answer is gone? Sam Hatchard, you can just overwrite a name, even with different types, there won't be a problem. a = 1 a = 5 a = [6, 7, 8] The actual creation and deletion is done for you automatically. So assigning a value to a name is more like pasting a name sticker onto an object, then later pasting it somewhere else.
16th Aug 2019, 5:04 PM
HonFu
HonFu - avatar
+ 1
more like overriding variable
17th Aug 2019, 9:02 AM
Sarvesh Yadav
Sarvesh Yadav - avatar