![]() |
|
[Tut] List Difference | The Most Pythonic Way - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] List Difference | The Most Pythonic Way (/thread-95922.html) |
[Tut] List Difference | The Most Pythonic Way - xSicKxBot - 06-27-2020 List Difference | The Most Pythonic Way Short answer: The most Pythonic way to compute the difference between two lists Code: l1Code: l2Code: [x for x in l1 if x not in set(l2)]![]() What’s the best way to compute the difference between two lists in Python? Code: a = [5, 4, 3, 2, 1]
b = [4, 5, 6, 7] # a - b == [3, 2, 1]
# b - a == [6, 7]In Python, you always have multiple ways to solve the same (or a similar) problem. Let’s have an overview in the following interactive code shell: https://trinket.io/embed/python/41397b54a0 Exercise: Run the code and think about your preferred way! Let’s dive into each of the methods to find the most Pythonic one for your particular scenario. Method 1: Set Difference The naive approach to solve this problem is to convert both lists into sets and use the set minus (or set difference) operation. Code: # Method 1: Set Difference
print(set(a) - set(b))
# {1, 2, 3}
print(set(b) - set(a))
# {6, 7}This approach is elegant because it’s readable, efficient, and concise. However, there are some unique properties to this method which you should be aware of:
If all three properties are acceptable to you, this is by far the most efficient approach as evaluated later in this article! However, how can you maintain the order of the original list elements while also allow duplicates? Let’s dive into the list comprehension alternative! Method 2: List Comprehension List comprehension is a compact way of creating lists. The simple formula is Code: [expression + context]
You can use list comprehension to go over all elements in the first list but ignore them if they are in the second list: Code: # Method 2: List Comprehension
print([x for x in a if x not in set(b)])
# [3, 2, 1]We used a small but effective optimization of converting the second list Code: bCode: x in bHere are the distinctive properties of this approach:
If you rely on these more powerful guarantees, use the list comprehension approach because it’s the most Pythonic one. Method 3: Simple For Loop Surprisingly, some online tutorials recommend using a nested for loop (e.g.,those guys): Code: # Method 3: Nested For Loop
d = []
for x in a: if x not in b: d.append(x)
print(d)
# [3, 2, 1]In my opinion, this approach would only be used by absolute beginners or coders who come from other programming languages such as C++ or Java and don’t know essential Python features like list comprehension. You can optimize this method by converting the list Code: bCode: if x not in bPerformance Evaluation Want to know the most performant one? In the following, I tested three different approaches: Code: import timeit init = 'l1 = list(range(100)); l2 = list(range(50))' # 1. Set Conversion
print(timeit.timeit('list(set(l1) - set(l2))', init, number = 10000)) # 2. List Comprehension
print(timeit.timeit('[x for x in l1 if x not in l2]', init, number = 10000)) # 3. List Comprehension + set
print(timeit.timeit('s = set(l2);[x for x in l1 if x not in s]', init, number = 10000)) '''
0.1620231000000001
0.5186101000000001
0.057180300000000184 '''You can run the code in our interactive Python shell: https://repl.it/@finxter/listdifferencespeed?lite=true Exercise: Run the code. Which is fastest and why? Although the first approach seems to be fastest, you now know that it has some disadvantages, too. (Loses duplicate info, loses ordering info.) From the two list comprehension approaches, the second one kills the first one in terms of runtime complexity and performance! Where to Go From Here? Enough theory, let’s get some practice! To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? Practice projects is how you sharpen your saw in coding! Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people? Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! |