0

I wanted to delete words from a list having length greater than 3. I used del (item) but it didn't worked. Here is the code:

lst=['XDA-OT','hi','loc','yeah']
for i in lst:
    if len(i)>3:
        del i

And the output:

lst
['XDA-OT', 'hi', 'loc', 'yeah']

Now I used remove() from Python List functions and I got the desired result.

Here is the code for the same:

lst=['XDA-OT','hi','loc','yeah']
for i in lst:
    if len(i)>3:
        lst.remove(i)

OUTPUT:

print(lst)
['hi', 'loc']

Also I have doubt regarding usage of index of list to delete a element from list but didn't understand how to frame the question.

I get IndexError whenever I delete a element using index. CODE:

lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
    if len(lst[i])>3:
        del lst[i]

OUTPUT ERROR:

IndexError                                
<ipython-input-35-617282928840> in <module>()
      1 for i in range(len(lst)):
----> 2     if len(lst[i])>3:
      3         del lst[i]

IndexError: list index out of range

Same using remove() function. CODE:

lst=['XDA-OT','hi','loc','yeah']
for i in range(len(lst)):
    if len(lst[i])>3:
        lst.remove(lst[i])

OUTPUT ERROR:

IndexError                                
<ipython-input-39-1d824ca5b061> in <module>()
      1 for i in range(len(lst)):
----> 2     if len(lst[i])>3:
      3         lst.remove(lst[i])

IndexError: list index out of range
3
  • 1
    del i is just deleting the variable i. That doesn't affect your list. Commented Jun 8, 2018 at 10:00
  • It is not a good choice to remove an item while iterating. Instead u can create a copy of lst using .copy or using slice [:] and iterate over and remove if from lst if some condition is met. Commented Jun 8, 2018 at 10:05
  • @abdul_niyas_pm you mean to say make a list copy and iterate over original and make changes to the copy? Commented Jun 8, 2018 at 10:13

4 Answers 4

1

As a general rule, I would avoid modifying an object I'm iterating on. This could lead to very odd behaviors.

Have you considered a solutions with list comprehension? It seems to me like the most pythonic implementation in this case.

lst = ['XDA-OT', 'hi', 'loc', 'yeah']
lst = [itm for itm in lst if len(itm) <= 3]
Sign up to request clarification or add additional context in comments.

2 Comments

List comprehension is working. But as you explained for IndexError if I use range(len(lst)-1) I am getting desired result. Why didn't here the IndexError came as here too elements are getting deleted.
When using list comprehension, a new list is created before reassigning the original list. This way, you don't have to worry about indexing. Here is a small example that you can check. Progress forward step by step, and see the variables that are used: pythontutor.com/…
1

You are having an index error because you are modifying the list as you go. The for loop receive a range(4) but in the end lst[4] does not exist anymore as you have deleted some items.

As for the question. del is a general function that delete an object whereas lst.remove() is a function of the list class. So in your case you can achieve what you want using both.

I would recommend that you go with the approach of @b3by as it makes usage of list comprehension which is faster in python than for loops as you where doing.

6 Comments

List comprehension is working. But as you explained for IndexError if I use range(len(lst)-1) I am getting desired result. Why didn't here the IndexError came as here too elements are getting deleted.
@user8810517 sorry but I do not understand what you are saying
I mean in my code containing range I used range(len(lst)-1) instead of range(len(lst)) this time I am not getting IndexError and elements are getting deleted. How?
@user8810517 because the result of this is range(3) and this is valid before the last call to remove. But this will not work if your list as another element to delete. Also do not forget to accept an answer ;)
sir in answer you wrote that as an element gets deleted last index is not valid. But in case of range(len(lst)-1) too elements get deleted so the last index must not be valid. And I think by accepting answer you mean to Upvote the answer. Well in that case I have upvoted the answer but since my reputation is less than 15 it won't be shown in public.
|
0

del deletes the desired element from wherever it is being held.

If used on a local variable, it'll delete the local variable so it cannot be accessed again, unless it's recreated (same thing applies on a global scope)

Same with list elements (del lst[2]) or dict items (del dct['MyKey'])


In your specific case, you are effectively deleting the local variable i, but not the element it refers to.

If you want to delete the specific element in the list, you don't have to store it on a separate variable:

 del lst[i]

However, I'd recommend to go with the second approach and use list.remove (or list.pop for that matter) as it's way more explicit and avoids undesired side effects.


As for your second question, you are getting an IndexError because on every iteration you reduce the size of the list (as you are removing elements from it), so you'll get to a point where your i is higher than the length of the list itself.

4 Comments

List comprehension is working. But as you explained for IndexError if I use range(len(lst)-1) I am getting desired result. Why didn't here the IndexError came as here too elements are getting deleted.
So it means that by using del(i) I am deleting the object "i" that is created on iteration on list and not the list element. Right?
@user8810517 Regarding your first question: It really depends on the list and the elements theirselves, so I wouldn't rely on it. For instance, if you try with the same list on a different order, such as ['XDA-OT','hi','yeah', 'loc'] you will see that using range(len(lst)-1) actually fails.
@user8810517 Regarding the second question: That is correct, you are just removing the variable from the scope. It will get recreated on the next loop iteration, so basically doing del i achieves nothing. However, you can see the behavior I described if you try to access it before the loop ends. For instance, if you add temp = i after del i you will get a NameError as i has been deleted.
0

With a del statement you would have to specify for the index. For example

del list[0]

Simply deleting a string value from the list will not work with the del function. However, the .remove() method will work in this situation. As the argument in .remove() simply pass the list item that you want to remove from the list. That can work in a for loop like so:

lst=['XDA-OT','hi','loc','yeah']
for i in lst:
   if len(i)>3:
      lst.remove(i)

print(lst)

And here is your output:

['hi', 'loc']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.