Just like how we use + to add a list to another list, or add another value to a variable, can we also subtract using -?
Well, you could try it and see:
my_list = [1,2,3] print(my_list + ) print("****") print(my_list - ) # Output: [1, 2, 3, 4] **** Traceback (most recent call last): File "C:\Users\path\to\test.py", line 4, in <module> print(my_list - ) TypeError: unsupported operand type(s) for -: 'list' and 'list'
… In general + and * have been redefined (technically, overloaded) by defining functionality in lists and strings, but their inverses, - and / have not.
So there is no way of subtracting a value aside from updating the list/variable/etc.?
Thanks a lot!
If you know the actual element that you want removed, there is lst.remove()
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] lst.remove('b') print(lst) # Output : ['a', 'c', 'd', 'e', 'f', 'g']
If you know the index, there is lst.pop()
lst.pop(4) print(lst) # Output: ['a', 'c', 'd', 'e', 'g']
You can also use slicing.
lst[1:4] =  print(lst) # Output: ['a', 'g']
+ has an obvious interpretation: concatenation
- is less obvious, and what would you be using it for?
Whatever the interpretation of
- is, it’s probably not the most difficult thing in the world to implement yourself.
collections.Counter would probably be useful since it does support subtraction and other set operations, it might even cover the use-case completely if the order of the elements isn’t important