Как удалить переменную в Python
Любая переменная занимает место в памяти. Не то чтобы это очень страшно на современных мощных компьютерах, однако иногда всё-таки необходимость удалить ссылку на переменную возникает.
В Python не обязательно заранее объявлять переменные. В любом месте программы вы может, например, написать так:
И это будет означать, что отныне в программе есть переменная х , которой присвоено значение 100 (подробнее о присваивании здесь). И теперь вы можете использовать эту переменную в своей программе: присваивать ей новые значения, вставлять в выражения и т.п.
Если же по какой-то причине вы больше не хотите видеть переменную х в своей программе, то вы можете удалить её с помощью инструкции del вот так:
После этого вы уже не сможете использовать переменную х в вашей программе, поскольку ссылка на неё будет удалена. Ссылка на переменную х отныне будет генерировать исключение NameError , и при попытке обращения к этой переменной будет выдано сообщение об ошибке:

Если же вам снова потребуется переменная х , то надо будет просто заново объявить её.
Инструкция del может быть использована и для других целей. Но об этом в другой раз. А сейчас для ясности можете посмотреть видео по теме данной статьи:
Ключевое слово Python del [С Примерами]
Основная цель Python dev – удалить объекты в программировании python. Здесь объектом могут быть переменные, списки или части списка.
- Автор записи
Ключевое слово Python del [С Примерами]
Все в Python является объектом, и почти все имеет атрибуты и методы. Таким образом, основная цель Python dev-удалить объекты на языке программирования python. Здесь объектом могут быть переменные, списки или части списка и т. Д.
Каждый объект является любым типом объекта Python. Обычно это переменные, но они могут быть функциями, модулями, классами.
Оператор del работает путем развязывания имени, удаляя его из набора имен, известных интерпретатору Python. Если эта переменная была последней оставшейся ссылкой на объект, то объект будет удален из памяти. Если, с другой стороны, другие переменные все еще ссылаются на этот объект, объект не будет удален.
Как удалить или удалить элемент в Python
Существует 3 различных способа удаления или удаления элементов в Python.
- удалить
- дель
- хлопок
Но в этом уроке мы узнаем о работе Python del.
Что такое Python del?
Python del обычно используется для удаления переменной из локального или глобального пространства имен. Это используется для восстановления памяти из данных, которые больше не нужны.
Синтаксис Python dev
Здесь del – это ключевое слово Python. Кроме того, obj_name может быть переменными, определяемыми пользователем объектами, списками, элементами в списках, словарями и т. Д.
Возвращаемое значение Python dev
Оператор Python dev ничего не возвращает.
Момент, Который Следует Отметить
Оператор del можно использовать для удаления элемента из списка, ссылаясь на его индекс, а не на его значение.
Теперь давайте перейдем непосредственно к примерам и проверим работу Python del statement.
Примеры инструкций Python dev
Давайте рассмотрим несколько примеров оператора del и попробуем удалить некоторые объекты.
Пример 1: Удаление переменной
Здесь вывод вышеприведенного примера “var” не определен. В этом примере мы получаем ошибку, потому что оператор Python del удаляет переменную. И теперь в памяти нет переменной с именем var .
Пример 2: Удаление первого элемента в списке
Объяснение:
В приведенном выше примере сначала мы создали наш список с именем list. Приведенный выше список содержит три элемента ( learn, python, pool ). После этого мы удалили первый элемент списка с помощью оператора del list[0]. Затем мы распечатали список после удаления первого элемента списка.
Пример 3: Удаление последнего элемента в списке
Объяснение:
В приведенном выше примере сначала мы создали наш список с именем list. Приведенный выше список содержит три элемента ( learn, python, pool ). После этого мы удалили последний элемент списка с помощью оператора del list[-1]. Затем мы распечатали список после удаления последнего элемента списка.
Пример 4: Удаление пользовательского объекта
Python Программа для удаления объекта класса с помощью Python del.
В приведенном выше примере мы удалили объект std с помощью del std. Впервые мы получаем желаемый результат. Это происходит потому, что мы не использовали ключевое слово del. Но после использования del std в нашем объекте. Мы получили ошибку имени, так как объект удален из памяти.
Пример 5: Удаление всех элементов в диапазоне
Объяснение:
Итак, в этом примере мы инициализировали список из 7 элементов. Затем мы удалили элементы в позиции 2-5. С помощью нарезки и Python del ключевое слово.
Пример 6: Программа Python для удаления ключа из словаря
В приведенном выше примере мы удалили пару ключ: значение из словаря. Изначально у нас в словаре есть 4 пары. После удаления ключа словаря x у нас есть только 3 элемента в словаре.
Python del: Дополнительные советы, замечания и примеры
Вы не можете удалить элементы кортежей и строк. Это потому, что кортежи и строки неизменны; объекты, которые не могут быть изменены после его создания.
Однако вы можете удалить весь кортеж или строку целиком.
Разница между remove, Python dev и pop в Python
- remove() удаляет соответствующий элемент/объект, тогда как del и pop удаляют элемент с определенным индексом.
- del и pop имеют дело с индексом. Единственное различие между ними заключается в том, что- pop return удалил значение из списка, а del ничего не возвращает.
- Pop-это единственный способ вернуть объект.
- Remove-это единственный объект, который ищет объект (а не индекс).
Вкратце: Используйте del для удаления элемента по индексу, pop для удаления его по индексу, если вам нужно возвращаемое значение, и remove для удаления элемента по значению.
Пример remove, Python dev и pop
Время выполнения
Вычислительная сложность (т. е. время выполнения или Big-O) выглядит следующим образом:
- del O(n)
- pop O(1)
- удалить O(n)
Обратите внимание, что эти времена выполнения являются наихудшими сценариями. Например, удаление элемента в начале списка занимает постоянное время.
Какой самый лучший способ удалить элемент в списке?
- Если вы хотите удалить определенный объект из списка, используйте метод remove.
- Если вы хотите удалить объект в определенном месте (индексе) в списке, вы можете использовать del или pop.
- Используйте pop, если вы хотите удалить и получить объект в определенном месте.
Разница между Python del и Присвоением None
Разница в том, что освободит все, на что ссылается, но сохранит имя, даже если оно просто ссылается на None (что является типом, NoneType).
С другой стороны, del x полностью удалит как имя, так и то, на что оно ссылается. Если после этого вы попытаетесь использовать x, будет выброшен NameError (или AttributeError в случае свойства объекта).
Таким образом, на практике, назначая None имени, вы все равно можете использовать его в выражениях, в то время как при использовании del имя полностью удаляется. В первом случае несколько href=”https://en.wikipedia.org/wiki/Byte”>байты необходимы для сохранения имени в памяти, в то время как более поздние полностью очищают все использование памяти. href=”https://en.wikipedia.org/wiki/Byte”>байты необходимы для сохранения имени в памяти, в то время как более поздние полностью очищают все использование памяти.
Когда я должен и не должен использовать ключевое слово del в Python?
Используйте оператор ‘del’, когда вы хотите удалить элемент из списка, и вы знаете, что вам никогда больше не нужно будет ссылаться на этот элемент.
Если вы хотите по какой-либо причине удержать удаленный элемент списка, используйте вместо этого метод “pop”.
Должен Читать:
- Как преобразовать строку в нижний регистр в
- Как вычислить Квадратный корень
- Пользовательский ввод | Функция ввода () | Ввод с клавиатуры
- Лучшая книга для изучения Python в 2020 году
Вывод
Python del-это полезное ключевое слово. Поначалу его синтаксис может сбить с толку. Но как только мы используем dell больше как оператор, а не вызов метода, это легко запомнить.
Удаление рекурсивно определяется очень похоже на то, как определяется назначение. Вместо того чтобы излагать его во всех подробностях, вот несколько советов. Удаление списка целей рекурсивно удаляет каждую цель слева направо.
Попробуйте запустить программы на вашей стороне и дайте мне знать, если у вас есть какие-либо вопросы.
How to delete or clear variable from memory in Python?
Computer memory is very important not just for storing data, code and instructions but also for the system’s performance. Variables are the simplest and most basic storage units. You must be knowing that Python variables are dynamically typed, i.e, they are declared as and when they are assigned/used.
Sometimes, even though you assigned a variable with some value in the program, you may realize later that that variable is not necessary. In such a scenario, you will want to delete that variable both from your program as well as your memory.
In this tutorial, you will understand how to delete a variable from the memory space in Python.
The del keyword
It is used to simply delete any Python object. (variables,arrays,lists,dictionaries etc).
Syntax: del(element to be deleted)
You can look into the below-coded example to understand this better.
Example 1: Deleting a variable
Note: The del method can be used not just with variables but with all Python objects like arrays, lists, dictionaries etc.
Example 2: Deleting a list
In this case, the program returns a NameError exception. This is because the variable you are trying to access no longer exists in the variable namespace.
However, the above del method only removes the variable from the namespace. It does not remove the variable from the memory space.
Well, so how do we permanently remove the variable and clear its memory?
The gc.collect() method in Python
The del method does not clear the variable from the memory. Hence, to clear the variable from memory you can resort to the gc.collect() method.
The gc.collect() method forces an immediate garbage collection of all generations. You can invoke the garbage collector as demonstrated below.
Example 1: Deleting a variable
In this case, you are deleting a from the memory space itself.
Just like the del method, you can invoke the gc.collect() for clearing the memory of not just variables but for all Python objects.
Example 2: Deleting a dictionary
Thus, you can use a combination of del() and gc.collect() to clear the variable from Python memory.
On a side note, though not very relevant, you can use the dir() method to get a list of the names of all the objects in the current scope.
3 Ways to Delete a Variable in Python (& Why?)

Python is an object-oriented programming language where we don’t have to worry about managing memory space in Python. It has a «Python memory manager», which is responsible for memory allocation and memory management, hence no need for any manual intervention. Yet, sometimes there are conditions that demand to have a look in the memory space.
Let’s take a look at the most basic memory unit, aka variables in Python, and see how memory works while dealing with them.
What is a Variable in Python?
A Variable is generally defined as a name assigned to that memory space that holds values. The word ‘variable’ itself refers to that the values can vary for the same space. You must be wondering if it is the same for all programming languages. You’ll be surprised to learn that, everything in Python is an object. Variables, Lists, Tuples, and even classes are instances.
Variables are references to the actual objects which hold the given value. That’s why in Python we don’t have to declare the variables or their data types before using them.
For example:
See how we have declared a variable and used a variable without any hassle of declaring data types or initializing.
Output:
Notice how the type(var1) returns <class ‘int’>. This implies that variable var1 is an instance of class integers.
Sounds Confusing? Don’t worry, let’s take a look into how memory management occurs in Python when a variable is declared.
How is Memory Managed in Python?
While working with Python, there are two types of memory:
1. Static Memory
2. Dynamic Memory
Python uses dynamic memory allocation, i.e. memory allocation occurs during runtime. The dynamic memory allocation uses a Heap data structure for implementation. Besides heap data structure, the Stack data structure is used to store the static memory. Don’t get confused between static memory and dynamic memory in Python.
Here, static memory refers to the function call stack. Recall the function call sequence stored using stack in Recursion. As compared to other programming languages, Python doesn’t involve manual memory management.
Python has a Python manager which manages the application data in memory, hence not much human intervention is required while dealing with memory space.
What occurs When we Declare a Variable in Python?
Variables in Python are references to not only constants or values, but they are also referenced to objects. When we declare a variable in Python, it creates an object in the Private Heap Space that stores the variable’s value. While the variable gets created in the Stack memory as a reference to the said object.
Hard to understand? Let’s look at an example. Assume you need to declare a variable; consider the variable name ‘a,’ with the value 5! Now, look at the image below to see what goes on behind the scenes!

As you see, the object, which stores the value (5) is created in the Private Heap Space while the variable/reference to that object gets created in stack memory. Now let’s consider creating another variable, say ‘b’, with the same value as ‘a’. Can you guess how the memory allocation will take place now?

The Python memory manager will generate another reference ‘b’ to the same object (storing 5) referenced to by ‘a’ since it’s the same value. As a result, there will be two references to the same object. Any change in either of the references will lead to breakage of their reference link to that object (storing 5) and say, the creation of another object.
You can think of variables in Pythons as pointers (as in C, and C++) to the objects.
Why do we need to Delete Variables?
Memory Management is one of the key consideration factors when dealing with software development in Python or any programming language. You must be wondering why this Memory Management is so important. You don’t even notice how it affects your code while writing any program.
Well, let me tell you, this is because you haven’t dealt with large software working on a large amount of data, or big data, yet. When dealing with big data, you’ll notice how this memory management affects your software’s overall efficiency and processing time.
Data structures were introduced for this reason!
How does Variables Deletion work?
As said earlier, Python has a Python memory manager, which is responsible for the allocation or de-allocation of the memory heap. The memory Heap in Python holds the objects and other data structures used in the program.
So, when a variable (a reference to an object) is no longer in use, the Python memory manager frees up the space, i.e. it removes the unnecessary object. This process of removing objects, which are no longer in use, is known as Garbage Collection.
Garbage Collector
Garbage Collector is a process that runs in the background of your Python program. As soon as you execute the Python program, the garbage collector also starts in the background. Hence, a garbage collector doesn’t need to be triggered or called upon specifically. This process runs on a regular basis and reclaims memory space from objects that are no longer needed by the program.
How’ll the Garbage Collector determine if a variable (object) should be deleted? Well, it’s pretty simple. Since Python has everything as objects, thus each object must have references. As discussed above, an object can have more than one reference. As soon as you create a variable, its object gets created in the Private Heap Space.
Now, let’s go back to our example. Since the object (storing 5) has two references ‘a’ and ‘b’. Now assume that you have to delete variable a. What do you think can occur in the memory?

So, the object won’t get deleted itself, since it has a reference (variable ‘b’) pointing at it. But the reference (variable ‘a’) is removed.
The number of references to an object is stored. This is known as Reference Counting in Python.
So, if we talk about the above example, our object (storing 5) had 2 references, variables ‘a’ and ‘b’. Hence, the Reference Count for our object (storing 5) will be 2. The Garbage Collector won’t discard this object till its Reference Count returns to zero. This means that until both the variables (‘a’ and ‘b’) get deleted, the object (storing 5) won’t be discarded.
Like the image below:

But this classical approach also falters when dealing with reference cycles. Now, let’s look at how to delete these variables in Python.
How to Delete Variables in Python?
So far we’ve discussed how memory allocation and de-allocation occur in Python. Although Python has a Garbage Collector and Memory Manager to deal with memory space automatically, there are some cases where you need to force memory cleaning.
For instance, when dealing with large amounts of data or developing software that consumes a lot of memory space. In Python, there aren’t many ways to delete variables. Some of the well-known methods are as follows:
01) Using the del keyword
Using the ‘del’ command is the most known and easiest method to delete variables in Python. The del keyword deletes the objects. Since everything in Python is an object, therefore lists, tuples and dictionaries can also be deleted using ‘del’. It has a really simple syntax.
Syntax: del variableName
For example, let’s delete a variable ‘a’.
You must be wondering how will you know if the variable is deleted. Try calling the variable again after deleting it.
Output:
Notice the NameError error obtained on calling the variable ‘a’ again, after deleting it. Hence, this proves that the variable ‘a’ is deleted using the del keyword.
While using the del keyword to delete variables in Python, you must be sure if you actually don’t want to access the variable later on at any stage in your program. Unnecessary deletion of variables (objects) can lead to error. You won’t be able to access these deleted variables, once deleted, from the program.
02) Deleting Multiple Variables in Python
You can also delete multiple variables together in Python using the del keyword. It is similar to initializing multiple variables in one line, separated by a comma.
Syntax : del variableName1, variableName2, variableName3
Example:
Deleting multiple variables is similar to deleting a variable in Python.
Output:
Note how the NameError error only pointed out variable ‘a’. Python is an interpreted language, which means that it interprets commands line-by-line. Since variable ‘a’ is the first undeclared variable encountered, hence the execution process pauses at the first error. Thus, the NameError error points out only the variable ‘a’.
03) Using dir() and globals()
You can also delete «All variables» in your program at once. By «All Variables» I mean the user-defined variables in the local or global scope of your program. As you know, the dir() method returns the all properties and methods of a specified object. Even when no object is referenced, it returns a list of all the variables and built-in methods used in your program.
You’ll notice that print(d) prints out the list of all the variables and methods in the given program.
Output:
Our user-defined variables (‘a’, ‘b’, and ‘c’) are at the bottom of the list. The double underscores (__) used as a suffix and prefix, distinguish a user-defined variable from a built-in variable or method.
At the same time, the globals() method returns a dictionary with all the global variables and symbols for the program along with their values. For example —
You’ll notice the difference between the dir() and globals() method with the following output:
At the end of the dictionary, note our defined variables are printed, along with their values.
Now, let’s begin with deleting these user-defined variables. You’ll need to check if the variable name holds any double underscores (‘__’) or not, in order to distinguish between user-defined and built-in variables.
Take note of the syntax for removing variables. First, we must determine whether the variable (object) is user-defined or not by looking for (‘__’) in the prefix. If the object is user-defined, we must remove it from the globals (). We can pass the object to globals() for deletion because it is a dictionary.
Output:
And Voila!! The user-defined variables are deleted. All at once!
Conclusion
Memory management is an important factor when it comes to the computational efficiency of a program or software. Although Python has its own Memory Manager and Garbage Collector, we can also trigger a garbage collector or delete variables in order to redeem the memory space. The ‘del’ keyword can be used to delete objects in Python. The word ‘object’ includes variables, lists, tuples, sets, dictionaries, and almost everything in Python. Try to implement the above methods to delete the other objects. You’ll be surprised with the result each time.