Clear a variable without destroying it

I have this piece of code:

a = "aa" b = 1 c = { "b":2 } d = [3,"c"] e = (4,5) letters = [a, b, c, d, e] 

And I want to do something about it, and they will let them go. Without losing your type.

Something like that:

 >>EmptyVars(letters) ['',0,{},[],()] 

Any clues?

+7
variables python
source share
2 answers

Do it:

 def EmptyVar(lst): return [type(i)() for i in lst] 

type() creates a type object for each value, which when called produces an "empty" new value.

Demo:

 >>> a = "aa" >>> b = 1 >>> c = { "b":2 } >>> d = [3,"c"] >>> e = (4,5) >>> letters = [a, b, c, d, e] >>> def EmptyVar(lst): ... return [type(i)() for i in lst] ... >>> EmptyVar(letters) ['', 0, {}, [], ()] 
+17
source share

Similarly, only type(i)() is replaced with i.__class__() :

 a = "aa" b = 1 c = {"b": 2} d = [3, "c"] e = (4, 5) letters = [a, b, c, d, e] def empty_var(lst): return [i.__class__() for i in lst] print(empty_var(letters)) ['', 0, {}, [], ()] 
0
source share

All Articles