Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Removing entries from ordered list, that are not in unordered list

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?

like image 731
Martin Avatar asked Dec 22 '22 02:12

Martin


1 Answers

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)

Benchmark!

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.

like image 194
Oleh Prypin Avatar answered May 09 '23 23:05

Oleh Prypin