# I have 3 lists:
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
L2 = [4, 7, 8]
L3 = [5, 2, 9]
# I want to create another that is L1 minus L2's memebers and L3's memebers, so:
L4 = (L1 - L2) - L3 # Of course this isn't going to work
I’m wondering, what is the “correct” way to do this. I can do it many different ways, but Python’s style guide says there should be only 1 correct way of doing each thing. I’ve never known what this was.
Here are some tries:
Now that I have had a moment to think, I realize that the
L2 + L3thing creates a temporary list that immediately gets thrown away. So an even better way is:Update: I see some extravagant claims being thrown around about performance, and I want to assert that my solution was already as fast as possible. Creating intermediate results, whether they be intermediate lists or intermediate iterators that then have to be called into repeatedly, will be slower, always, than simply giving
L2andL3for the set to iterate over directly like I have done here.All other alternatives (that I can think of) will necessarily be slower than this. Doing the loops ourselves, for example, rather than letting the
set()constructor do them, adds expense:Using iterators, will all of the state-saving and callbacks they involve, will obviously be even more expensive:
So I believe that the answer I gave last night is still far and away (for values of “far and away” greater than around 5µsec, obviously) the best, unless the questioner will have duplicates in
L1and wants them removed once each for every time the duplicate appears in one of the other lists.