-1

I'm learning python and I wanted to create some code which would take a list of lists, check if each row had a particular value for a given index number and if it did, delete the entire row. Now I intuitively decided to use del to delete the rows, but when I printed out the list with the removed values, I got the same list back. I added a counter to check if there were any rows which had the value to be removed and they did indeed exist. The problem I have is illustrated by the following code:

test_list=[1,2,3,4,5]
for element in test_list:
    if element == 1:
        del element
print (test_list)

Output

[1,2,3,4,5]

What is the function of del, if not to delete the element here?

Vishal Jain
  • 443
  • 4
  • 17
  • The given for loop code should be checked. It is incorrect. Simply use either `del()`, `remove()` or `pop()` function for performing your task. – Darshan Jain Feb 19 '20 at 05:58

4 Answers4

2

Actually, del is doing nothing in your code. It's just deleting a local binding to the iteration variable (not to the list element, even though they point to the same object). This has no effect on the list, and anyway in the next iteration the variable will get assigned to the next value.

For the general case, if you wanted to delete an element in the list using del (and you didn't know where it's located), this is what you'd have to do:

delete_me = 1
for i in range(len(test_list)-1, -1, -1):
    if test_list[i] == delete_me:
        del test_list[i]

Notice how del works for lists, and the fact that we need to traverse the list in reverse to avoid problems when modifying a list at the same time we're iterating over it.

There is a simpler way, though - and that is not using del at all, but a list comprehension:

delete_me = 1
test_list = [x for x in test_list if x != delete_me]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

del is removing the reference to the object element. Which is not the reference to the list element.

Layo
  • 677
  • 6
  • 16
0

You are deleting a temporary variable named element which is created at each iteration on test_list.

If you want to remove an item from a list, use remove, or del list[index]

More here: https://www.tutorialspoint.com/python/list_remove.htm
How to remove an element from a list by index?
Is there a simple way to delete a list element by value?

olinox14
  • 6,177
  • 2
  • 22
  • 39
-2

The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.

https://www.w3schools.com/python/ref_keyword_del.asp

  • 1
    I think the source was [w3schools](https://www.w3schools.com/python/ref_keyword_del.asp) – Layo Jul 03 '19 at 10:07
  • Downvoting because In any case, the answer is not really explanatory. The OP is clearly confused about the effect of del on the list and your answer did poorly to address that. – Layo Jul 03 '19 at 10:13