Use a list comprehension:
[item for item in x if item not in y]
If you want to use the -
infix syntax, you can just do:
class MyList(list): def __init__(self, *args): super(MyList, self).__init__(args) def __sub__(self, other): return self.__class__(*[item for item in self if item not in other])
you can then use it like:
x = MyList(1, 2, 3, 4) y = MyList(2, 5, 2) z = x - y
But if you don’t absolutely need list properties (for example, ordering), just use sets as the other answers recommend.
Related Posts:
- How do I copy a file in Python?
- Praw & Discord.py: The bot keep sending the same meme. I want the bot to send different meme whenever it is asked
- How can I make a time delay in Python? [duplicate]
- How to reset index in a pandas dataframe? [duplicate]
- Why am I getting “IndentationError: expected an indented block”? [duplicate]
- Dijkstra’s algorithm in python
- How to use “raise” keyword in Python [duplicate]
- List changes unexpectedly after assignment. Why is this and how can I prevent it?
- How to resolve TypeError: can only concatenate str (not “int”) to str [duplicate]
- TypeError: ‘float’ object is not subscriptable
- How do I merge two dictionaries in a single expression (taking union of dictionaries)?
- How do I create an empty array/matrix in NumPy?
- TypeError: cannot perform reduce with flexible type
- ValueError : I/O operation on closed file
- Regex: AttributeError: ‘NoneType’ object has no attribute ‘groups’
- Internal Redirect in Flask
- How do I select rows from a DataFrame based on column values?
- How do I concatenate two lists in Python?
- How do I get the row count of a Pandas DataFrame?
- How can I randomly select an item from a list?
- Unable to plot Double Bar, Bar plot using pyplot for ndarray
- Error”Can only compare identically-labeled Series objects” and sort_index
- How to download a file over HTTP?
- ImportError: numpy.core.multiarray failed to import
- Index Error: list index out of range (Python) [duplicate]
- Difference between os.getenv and os.environ.get
- How to check if the string is empty?
- Get the data received in a Flask request
- How to do superscripts and subscripts in Jupyter Notebook?
- Cannot install Beautiful Soup in Anaconda Python 3.6.4 Windows 10
- ImportError: cannot import name
- heroku: no default language could be detected for this app
- “VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path”
- Syntax behind sorted(key=lambda: …)
- convert nan value to zero
- Python Error io.UnsupportedOperation: not readable
- TypeError: ‘DataFrame’ object is not callable
- Empty set literal?
- How can I check file size in Python?
- What is the point of float(‘inf’) in Python?
- Why do I get a “referenced before assignment” error when assigning to a global variable in a function?
- Add list to set?
- Python list directory, subdirectory, and files
- xlrd.biffh.XLRDError: Excel xlsx file; not supported
- Convert XML to CSV file
- AttributeError: Module Pip has no attribute ‘main’
- Best way to replace multiple characters in a string?
- What does the Python error “name ‘self’ is not defined” mean?
- Python wildcard search in string
- How to have an array of arrays in Python
- How to increase plt.title font size?
- What is the meaning of single and double underscore before an object name?
- What is the difference between np.mean and tf.reduce_mean?
- How do I combine two dataframes?
- How to fix “Attempted relative import in non-package” even with __init__.py
- How to convert string to binary?
- Make list of arrays in python
- In Python, what is `sys.maxsize`?
- How to check if type of a variable is string?
- How to remove \n from a list element?
- What are the causes of overflow encountered in double_scalars besides division by zero?
- How can I check for NaN values?
- How do I get the parent directory in Python?
- How can I install the latest Anaconda with wget
- Youtube_dl : ERROR : YouTube said: Unable to extract video data
- Creating lowpass filter in SciPy – understanding methods and units
- Get Confusion Matrix From a Keras Multiclass Model
- Insert a row to pandas dataframe
- How to make a set of lists
- How to start from second index for for-loop
- How to install PyGame on Python 3.4?
- bbox_to_anchor and loc in matplotlib
- plotly: TypeError: cannot convert dictionary update sequence element #0 to a sequence
- scrapy run spider from script
- OverflowError: (34, ‘Result too large’)
- Get an attribute value based on the name attribute with BeautifulSoup
- Efficiently sorting a numpy array in descending order?
- How to fix ‘RuntimeWarning: divide by zero encountered in double_scalars’
- ImportError: No module named ‘MySQL’
- how to read json object in python
- Pandas: sum up multiple columns into one column without last column
- Open File in Another Directory (Python)
- Checking if a string can be converted to float in Python
- Convert floats to ints in Pandas?
- How to set NotebookApp.iopub_data_rate_limit and others NotebookApp settings in JupyterHub?
- set object is not JSON serializable
- Count Vowels in String Python
- coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
- Python cant convert ‘list’ object to str error [closed]
- python flask import error
- Python Brute Force algorithm
- How can I install a .egg Python package on Windows (attempt using easy_install not working)
- Case insensitive regular expression without re.compile?
- replace characters not working in python [duplicate]
- Python Remove last char from string and return it
- python ValueError: invalid literal for float()
- Anaconda “failed to create process”
- How to pass a list by reference?
- How to add a background image into pygame?
- OCaml mod function returns different result compared with %