I have a list that contains strings. I want to drop out the ones that have specific strings using python.
For example:
my_sample_list = ["I am practicing Python", "I am practicing Java", "I am practicing SQL"]
I want to drop out the element that contains "SQL"
and I will be left with:
my_new_sample_list = ["I am practicing Python", "I am practicing Java"]
How can I do that in python, please? Any help would be appreciated.
CodePudding user response:
Iterate over the strings and check if the pattern is contained in it or not.
my_sample_list = ["I am practicing Python", "I am practicing Java", "I am practicing SQL"]
pattern = 'SQL'
my_new_sample_list = [s for s in my_sample_list if pattern not in s]
CodePudding user response:
Turn them to sets and do an intersection and back to list
list(set(my_sample_list).intersection(set(my_new_sample_list)))
['I am practicing Java', 'I am practicing Python']
CodePudding user response:
Two basic approaches:
- Build a new array containing only valid entries:
new=[ entry if 'SQL' not in entry for entry in old ]
- Advantage: pretty foolproof
- Disadvantage: double the memory
- Remove the element with the invalid entry
- Advantage: very low resource use
- Disadvantage: not trivial to write. Easy to create weird bugs