﻿ Python: Empty a variable without destroying it - w3resource

Python: Empty a variable without destroying it

Python Basic: Exercise-122 with Solution

Write a Python program to empty a variable without destroying it.

type() returns the type of an object, which when called produces an 'empty' new value.

Sample data: n=20
d = {"x":200}
Expected Output: 0
{}

Sample Solution-1:

Python Code:

``````# Define a variable n with a value of 20.
n = 20

# Define a dictionary d with a key "x" and a value of 200.
d = {"x": 200}

# Define a list l with elements 1, 3, and 5.
l = [1, 3, 5]

# Define a tuple t with elements 5, 7, and 8.
t = (5, 7, 8)

# Print the type of n and create an instance of that type with no arguments.
print(type(n)())

# Print the type of d and create an instance of that type with no arguments.
print(type(d)())

# Print the type of l and create an instance of that type with no arguments.
print(type(l)())

# Print the type of t and create an instance of that type with no arguments.
print(type(t)())
```
```

Sample Output:

```0
{}
[]
()
```

Sample Solution-2:

Python Code:

``````# Define a function called Empty_Var that takes a list lst as input.
def Empty_Var(lst):
# Create a new list by initializing elements of the same type as those in the input list.
return [type(i)() for i in lst]

# Create a list called lst containing various types of objects.
lst = ["python", {"x": 12}, [10, 12, "sfsd"], (4, 5), 200]

# Print the original objects contained in the list.
print("Original objects:")
print(lst)

# Print a message and the result of emptying the variables without destroying them.
print("\nEmpty the said variables without destroying them:")
print(Empty_Var(lst))
```
```

Sample Output:

```Original objects:
['python', {'x': 12}, [10, 12, 'sfsd'], (4, 5), 200]

Empty the said variables without destroying it:
['', {}, [], (), 0]
```

Flowchart:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿