Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and delete list elements if matching a string

I have a list of strings stringlist = ["elementOne" , "elementTwo" , "elementThree"] and I would like to search for elements that contain the "Two" string and delete that from the list so my list will become stringlist = ["elementOne" , "elementThree"]

I managed to print them but don't really know how to delete completely from the list using del because i don't know the index or by using stringlist.remove("elementTwo") because I don't know the exact string of the element containing "Two"

My code so far:

for x in stringlist:
   if "Two" in x:
       print(x)
like image 524
faceoff Avatar asked Dec 19 '22 03:12

faceoff


1 Answers

Normally when we perform list comprehension, we build a new list and assign it the same name as the old list. Though this will get the desired result, but this will not remove the old list in place.

To make sure the reference remains the same, you must use this:

>>> stringlist[:] = [x for x in stringlist if "Two" not in x]
>>> stringlist
['elementOne', 'elementThree']

Advantages:
Since it is assigning to a list slice, it will replace the contents with the same Python list object, so the reference remains the same, thereby preventing some bugs if it is being referenced elsewhere.

If you do this below, you will lose the reference to the original list.

>>> stringlist = [x for x in stringlist if "Two" not in x]
>>> stringlist
['elementOne', 'elementThree']

So to preserve the reference, you build the list object and assign it the list slice.

To understand the subtle difference:

Let us take a list a1 containing some elements and assign list a2 equal to a1.

>>> a1 = [1,2,3,4]
>>> a2 = a1

Approach-1:

>>> a1 = [x for x in a1 if x<2]

>>> a1
[1]
>>> a2
[1,2,3,4]

Approach-2:

>>> a1[:] = [x for x in a1 if x<2]

>>> a1
[1]
>>> a2
[1]

Approach-2 actually replaces the contents of the original a1 list whereas Approach-1 does not.

like image 163
Rahul Gupta Avatar answered Jan 11 '23 08:01

Rahul Gupta