Python Tip #164 (of 365):
Thinking in terms of a Venn diagram? You need a set. 🧵
Need to find all items in one collection but not another? Intersect two collections? Check what's unique to each?
Python's sets support set arithmetic for these questions.
#Python #DailyPythonTip
🗺️ June 13, 2026
5/5 countries in 6/13 guesses
🟢🟢🟢🟢🟡
whereabouts.earth/daily/
#Whereabouts
It's worth memorizing these about Python's built-in data structures:
lists:
• Indexing (items[i]): O(1)
• Append/pop from end: O(1)
• Insert/pop from beginning: O(n)
• Containment check (x in items): O(n)
• Sorting: O(n log n)
sets & dicts:
• Containment check (x in items): O(1)
• Add/remove: O(1)
The most common time complexities you'll see in Python:
O(1) (constant time): work doesn't grow (indexing)
O(N) (linear time): work grows with the data (looping)
O(n log n): a bit slower than linear (sorting)
O(n * n) (quadratic): work grows with square of the data (loop within a loop)
Whenever you find yourself wanting to compare the items in two collections, consider whether set arithmetic might help.
For example, to find which required fields are missing:
required = {"name", "email", "password"}
provided = set(form_data.keys())
missing = required - provided
More 👇
If you find yourself doing containment checks inside a loop, your code has an O(n) operation for each step of another O(n) operation, making it O(n*n).
For more on this topic, see my article on the time complexities of different data structures in Python:
pym.dev/time-complex...
Python Tip #163 (of 365):
Commit the most important time complexities to memory. 🧵
Time complexity is about how your code slows as your data grows (a phrase from @nedbat.com).
You don't need a Computer Science degree to benefit from knowing some common complexities.
#Python #DailyPythonTip
“Unlike many programming languages, you can accomplish quite a bit in Python without ever making a class.”
Read more 👉 pym.dev/when-are-cla...
#Python #classes
This O(n*n) code may take seconds over a large list:
for word in words:
if word[::-1] in words:
print(word)
While this O(n) code may takes milliseconds:
word_set = set(words)
for word in words:
if word[::-1] in word_set:
print(word)
Python's sets support set arithmetic using operators.
>>> a = {1, 2, 3, 4, 7}
>>> b = {1, 3, 5, 7, 9}
Union:
>>> a | b
{1, 2, 3, 4, 5, 7, 9}
Intersection:
>>> a & b
{1, 3, 7}
Asymmetric difference:
>>> a - b
{2, 4}
Symmetric difference:
>>> a ^ b
{2, 4, 5, 9}