I have two lists:
ordered = ['salat', 'baguette', 'burger', 'pizza']
unordered = ['pizza', 'burger']
Now I want to remove all entries from the ordered list, that are not in the unordered list while preserving the ordering.
How can I do this?
ordered = [item for item in ordered if item in unordered]
This method creates a new list based on the old ones using Python's list comprehension.
For large amounts of data, turning the unordered list into a set first, as people suggested in comments, makes a huge difference in performance, e.g.:
unordered = set(unordered)
ordered: 5000 items, unordered: 1000 items
0.09561s without set
0.00042s with set
For 10/2 items the time is almost the same, so it's good to always use a set, no matter what the data size is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With