![]() |
|
[Tut] The Most Pythonic Way to Compare Two Lists in Python - 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] The Most Pythonic Way to Compare Two Lists in Python (/thread-95943.html) |
[Tut] The Most Pythonic Way to Compare Two Lists in Python - xSicKxBot - 06-28-2020 The Most Pythonic Way to Compare Two Lists in Python Problem: Given are two lists Code: l1Code: l2
Example: You start with two lists. Code: l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3] # 1. Boolean Comparison
result = False # 2. Difference
result = [4, 5]Let’s discuss the most Pythonic ways of accomplishing these problems. We start with five ways to perform the Boolean comparison and look at five ways to perform the simple difference, next. Boolean Comparison Short answer: The most Pythonic way to check if two ordered lists Code: l1Code: l2Code: l1 == l2Code: True![]() Problem: Given are two lists Code: l1Code: l2Code: TrueCode: TrueCode: FalseExamples: Code: l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 5, 4]
# compare(l1, l2) --> False l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3, 4, 5]
# compare(l1, l2) --> TrueLet’s discuss the most Pythonic ways of solving this problem. Here’s a quick interactive code overview: https://repl.it/@finxter/ScaryWingedString?lite=true Exercise: Glance over all methods and run the code. What questions come to mind? Do you understand each method? Read on to learn about each method in detail! Method 1: Simple Comparison Not always is the simplest method the best one. But for this particular problem, it is! The equality operator Code: ==Code: # 1. Simple Comparison
def method_1(l1, l2): return l1 == l2 l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_1(l1, l2))
# FalseSo, if you just want to learn about the most Pythonic way to solve this problem, look no further. But if you want to dive into the wonderful world of Python, learning about different interesting and powerful Python functions, read on! Method 2: Simple For Loop The following method is what you’d see from a coder coming from another programming language or from a beginner who doesn’t know about the equality operator on lists (see Method 1). Code: # 2. Simple For Loop
def method_2(l1, l2): for i in range(min(len(l1), len(l2))): if l1[i] != l2[i]: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_2(l1, l2))
# FalseIn the code, you iterate over all indices from 0 to the last position of the smallest list as determined by the part Code: min(len(l1), len(l2))Code: l1[i] != l2[i]Code: FalseIf you went through the whole loopwithout returning Code: FalseCode: len(l1) == len(l2)Code: TrueA lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the Code: zip()Method 3: zip() + For Loop The zip functiontakes a number of iterables and aggregates them to a single one by combining the i-th values of each iterable into a tuple for every i. Let’s see how you can use the function to make the previous code more concise: Code: # 3. Zip + For Loop
def method_3(l1, l2): for x, y in zip(l1, l2): if x != y: return False return len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_3(l1, l2))
# FalseInstead of iterating over indices, you now iterate over pairs of elements (the ones zipped together). If the lists have different sizes, the remaining elements from the longer list will be skipped. This way, element-wise comparison becomes simpler and no elaborate indexing schemes are required. Avoiding indices by means of the Code: zip()Method 4: sum() + zip() + len() But true Python coders will often avoid a for loop and use a generator expression instead.
Code: # 4. Sum + Zip + Len
def method_4(l1, l2): num_equal = sum(x == y for x, y in zip(l1, l2)) return num_equal == len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_4(l1, l2))
# False print(method_4([1, 2], [1, 2]))
# TrueFrom the methods except the first one using the Code: ==Code: zip(), len(), and sum()You could also write this in a single line of code! Code: sum(x == y for x, y in zip(l1, l2)) == len(l1) == len(l2)If you love Python one-liners, check out my new book Python One-Liners with internationally renowned publisher NoStarch press. (Amazon Link) Method 5: map() + reduce() + len() The last method is just to train your functional programming skills. Code: # 5. map() + reduce() + len()
from functools import reduce
def method_5(l1, l2): equal = map(lambda x, y: x == y, l1, l2) result = reduce(lambda x, y: x and y, equal) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# TrueThe Code: map()Code: reduce()Code: andCode: all()Method 6: map() + all() This is the same as the previous method—but using the Code: all()Code: reduce()Code: # 6. map() + all()
def method_6(l1, l2): result = all(map(lambda x, y: x == y, l1, l2)) return result and len(l1) == len(l2) l1 = [1, 2, 3, 4, 5]
l2 = [1, 2, 3]
print(method_5(l1, l2))
# False print(method_5([1, 2, 3], [1, 2, 3]))
# TrueIf you want to learn something new every day, join my free Python email series for continuous improvement in Python and computer science. Original article: The Most Pythonic Way to Check if Two Ordered Lists Are Identical Difference 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]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 bOriginal Article: List Difference | The Most Pythonic Way 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! |