python 3.x - Find and delete list elements if matching a string -
i have list of strings stringlist = ["elementone" , "elementtwo" , "elementthree"]
, search elements contain "two"
string , delete list list become stringlist = ["elementone" , "elementthree"]
i managed print them don't know how delete list using del
because don't know index or using stringlist.remove("elementtwo")
because don't know exact string of element containing "two"
my code far:
for x in stringlist: if "two" in x: print(x)
normally when perform list comprehension, build new list , assign same name old list. though desired result, not remove old list in place.
to make sure reference remains same, must use this:
>>> stringlist[:] = [x x in stringlist if "two" not in x] >>> stringlist ['elementone', 'elementthree']
advantages:
since assigning list slice, it replace contents same python list object, reference remains same, thereby preventing bugs if being referenced elsewhere.
if below, lose reference original list.
>>> stringlist = [x x in stringlist if "two" not in x] >>> stringlist ['elementone', 'elementthree']
so preserve reference, build list object , assign list slice.
to understand subtle difference:
let take list a1
containing elements , assign list a2
equal a1
.
>>> a1 = [1,2,3,4] >>> a2 = a1
approach-1:
>>> a1 = [x x in a1 if x<2] >>> a1 [1] >>> a2 [1,2,3,4]
approach-2:
>>> a1[:] = [x x in a1 if x<2] >>> a1 [1] >>> a2 [1]
approach-2 replaces contents of original a1
list whereas approach-1 not.
Comments
Post a Comment