Skip to content Skip to sidebar Skip to footer

Python Remove Element In List

I have a question say I have two list, and each of them contains couple of strings a = ['x', 'y', 'z', 't'] b = ['xyz', 'yzx', 'xyw'] I want to delete xyw in list b, because w is

Solution 1:

You could check that all of the letters in each string are contained in your list a then filter out strings using a list comprehension.

>>>a = ['x', 'y', 'z']>>>b = ['xyz', 'yzx', 'xyw']>>>[i for i in b ifall(j in a for j in i)]
['xyz', 'yzx']

Solution 2:

>>>a = ['x', 'y', 'z']>>>b = ['xyz', 'yzx', 'xyw']>>>for element in b:...ifnotall(i in a for i in element):...        b.remove(element)...>>>b
['xyz', 'yzx']
>>>

Correcttion: I shouldn't delete during iterating. So following like the solution above fits

>>>a = ['x', 'y', 'z']>>>b = ['xyz', 'yzx', 'xyw']>>>b = [i for i in b ifall(j in a for j in i)]>>>b
['xyz', 'yzx']
>>>

Post a Comment for "Python Remove Element In List"