In Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
... which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5) is a small set of elements), using a set is faster as the in operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
Answer from aluriak on Stack OverflowIn Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
... which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5) is a small set of elements), using a set is faster as the in operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
You can do it in one line by converting your lists to sets and using set.difference:
item_list = ['item', 5, 'foo', 3.14, True]
list_to_remove = ['item', 5, 'foo']
final_list = list(set(item_list) - set(list_to_remove))
Would give you the following output:
final_list = [3.14, True]
Note: this will remove duplicates in your input list and the elements in the output can be in any order (because sets don't preserve order). It also requires all elements in both of your lists to be hashable.
Remove multiple elements from a list
How to remove words in a list from a list of strings?
Python best way to remove multiple strings from string - Stack Overflow
How to remove multiple substrings at the end of a list of strings in Python? - Stack Overflow
Hello, I have created a list. The list has duplicate items, and I want to removed both the items from list.
a = ["Grapes", "Pineapple", "Coconut", "Mango", "Apple", "Banana", "Orange", "Mango"]
I used remove method to remove the items from list. But remove method is removing only first item instead of both.
a.remove("Mango")I have a list of strings:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
I want to remove words that occur in the following list:
remove = ['evil', 'money', 'poetic', 'lift']
The result I am seeking is:
result = ['[power, brilliant]', '[shock, watch]']
It's also important that the words that remain stay in a list themselves e.g., [power, brilliant].
What I have tried:
# attempt 1:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']
result = [' '.join(w for w in str(list_strings).split() if w.lower() not in remove)
for place in places
]
print(result)
# attempt 2:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']
for each in list_strings:
for i in remove:
x = each.replace(i, "")
print(x)You can use this example to remove selected last words from the list of string:
lst =['dont strip this', 'puppies com', 'company abc org', 'company a com', 'python limited']
to_strip = {'limited', 'com', 'org'}
out = []
for item in lst:
tmp = item.rsplit(maxsplit=1)
if tmp[-1] in to_strip:
out.append(tmp[0])
else:
out.append(item)
print(out)
Prints:
['dont strip this', 'puppies', 'company abc', 'company a', 'python']
If i understand this correctly you always want to remove the last word in each sentance?
If that's the case this should work:
lst =['puppies com', 'company abc org', 'company a com', 'python limited']
for i in lst:
f = i.rsplit(' ', 1)[0]
print(f)
Returns:
puppies
company abc
company a
python
rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string). As described here
This is also available in the python doc here.
You're trying to change the list at the same time as modifying it. Try creating a new list with the filtered objects instead.
mylist = [x for x in mylist if 'a' in x]
See more methods here: How to remove items from a list while iterating?
Personally, I think, Best practice is creating new list and returning it, than removing elements from existing list. so,
def new_list(myList):
newlist = []
for word in myList:
if 'a' in word:
newlist.append(word)
return newlist
Well, first I would say that pop is not the best option for the procedure. pop will return the value, you are only looking to remove it. To remove an element from a list given its index you can do:
my_list = [1,2,3,4]
del(my_list[2])
Nevertheless, going through a for loop while removing the elements that are part of it is not a good idea. It would be best to create a new list with only the elements you want.
my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = []
for value_str in my_list:
if 'a' != value_str[0]:
my_new_list.append(value_str)
This can also be done more concisely using list comprehension. The snippet below does the same thing as the one above, but with less code.
my_list = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
my_new_list = [value_str for value_str in my_list if value_str[0] != 'a']
Tim already gave you that snippet as an answer, but I felt that given the question it would be better to give you a more descriptive answer.
This is a good link to learn more about list comprehensions, if you are interested (they are pretty neat): Real Python - List Comprehensions
Using a list comprehension we can try:
l = ['fast', 'attack', 'slow', 'baft', 'attack', 'baft']
output = [x for x in l if x[0] != 'a']
print(output) # ['fast', 'slow', 'baft', 'baft']