On 6/5/2022 1:22 PM, Benedict Verhegghe wrote:
Op 5/06/2022 om 18:47 schreef David Mertz, Ph.D.:
Sure, that's nice enough code and has the same big-O complexity. I suspect set difference is a little faster (by a constant multiple) because it hits C code more, but I haven't benchmarked.

The OP said the elements were from fnmatch though, which explicitly does not promise order. So really it's just whether you like your code or this better aesthetically:

     list(set(b) - set(a))

I benchmarked it and indeed the list difference is a little faster.
>>> timeit.timeit('s=set(b); [x for x in a if x not in s]', setup='a = list(range(10000)); b = list(range(1000))', number=1000)
0.6156670850032242
>>> timeit.timeit('list(set(a)-set(b))', setup='a = list(range(10000)); b = list(range(1000))', number=1000)
0.43649216600169893

And what's more, it seems to also preserve order. I guess because a set is implemented like a dict, and will preserve order of you only remove some elements from the set.

A set doesn't guarantee order at all, and indeed it does not preserve creation order:

>>> s = set([10, 20, 1])
>>> s
{1, 10, 20}

You're seeing an accidental byproduct of the implementation.

Eric

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/WZFC3WAOMTQ2UQIMGBJ2VTBBOE5XUWBR/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to