06-28-2020, 01:18 PM
The Most Pythonic Way to Compare Two Lists in Python
Problem: Given are two lists and . You want to perform either of the following:
Example: You start with two lists.
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 and are identical, is to use the operator for element-wise comparison. If all elements are equal and the length of the lists are the same, the return value is .
![[Image: probform-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/probform-1024x576.jpg)
Problem: Given are two lists and . You want to perform Boolean Comparison: Compare the lists element-wise and return if your comparison metric returns for all pairs of elements, and otherwise .
Examples:
Let’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 compares a list element-wise—many Python coders don’t know this!
So, 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).
In the code, you iterate over all indices from 0 to the last position of the smallest list as determined by the part. You then check if both elements at the same position are different. If they are different, i.e., , you can immediately return because the lists are also different.
If you went through the whole loopwithout returning, the list elements are similar. But one list may still be longer! So, by returning , you ensure to only return if (1) all elements are equal and (2) the lists have the same length.
A lot of code to accomplish such a simple thing! Let’s see how a better coder would leverage the function to reduce the complexityof the code.
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:
Instead 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 function is a more Pythonic way for sure!
Method 4: sum() + zip() + len()
But true Python coders will often avoid a for loop and use a generator expression instead.
From the methods except the first one using the operator, this is the most Pythonic way due to the use of efficient Python helper functions like and generator expressions to make the code more concise and more readable.
You could also write this in a single line of code!
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.
The function combines all pairs of elements to Boolean values (are the two elements equal?). The function combines all Boolean values performing an operation. Sure, you can also use the more concise variant using the function:
Method 6: map() + all()
This is the same as the previous method—but using the function instead of to combine all Boolean values in a global and operation.
If 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 and is the list comprehension statement . This works even if you have duplicate list entries, it maintains the original list ordering, and it’s efficient due to the constant runtime complexity of the set membership operation.
![[Image: listDifference-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/listDifference-1024x576.jpg)
What’s the best way to compute the difference between two lists in Python?
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.
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.
You can use list comprehension to go over all elements in the first list but ignore them if they are in the second list:
We used a small but effective optimization of converting the second list to a set first. The reason is that checking membership is muchfaster for sets than for lists. However, semantically, both variants are identical.
Here 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):
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 to a set first to accelerate the check by a significant margin.
Original 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!
Problem: Given are two lists
Code:
l1Code:
l2- 1. Boolean Comparison: Compare the lists element-wise and return if your comparison metric returnsCode:
Truefor all pairs of elements, and otherwiseCode:True.Code:False
- 2. Difference: Find the difference of elements in the first list but not in the second.
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![[Image: probform-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/probform-1024x576.jpg)
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.
- You first create an iterable of Boolean values using the generator expression .Code:
x == y for x, y in zip(l1, l2)
- Then, you sumup over the Boolean values (another trick of pro coders) to find the number of elements that are the same and store it in variable .Code:
num_equal
- Finally, you compare this with the length of both lists. If all three values are the same, both lists have the same elements and their length is the same, too. They are equal!
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)]![[Image: listDifference-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/listDifference-1024x576.jpg)
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:
- The result is a setand not a list. You can convertit back to a list by using the constructor.Code:
list(...)
- All duplicatedlist entries are removed in the process because sets cannot have duplicated elements.
- The order of the original list is lost because sets do not maintain the ordering of the elements.
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]- Expression: What to do with each list element?
- Context: What elements to select? The context consists of an arbitrary number of andCode:
forstatements.Code:if
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:
- The result of the list comprehension statement is a list.
- The order of the original list is maintained.
- Duplicate elements are maintained.
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!

