The Most Pythonic Way to Check If a List Contains an Element

The standard way of checking if an element exists in a list is to use the in keyword. For example, ‘Alice’ in [1, ‘Alice’, 3] will return True while the same returns False for ‘Bob’. If you need to check more complicated conditions, use the any(condition(x) for x in list) function with a generator expression. … Read more

string.join(list) vs list.join(string) | Why Python’s Creators Chose The Former

If you’re like me, you may have asked yourself the following question: Why is it string.join(list) instead of list.join(string) in Python? ? The join method works with any iterable, not just with lists. Therefore, you’d have to implement it in hundreds of classes instead of just one (in the string class). Additionally, join() works only … Read more

How to Intersect Multiple Sets in Python?

To intersect multiple sets, stored in a list l, use the Python one-liner l.pop().intersection(*l) that takes the first set from the list, calls the intersection() method on it, and passes the remaining sets as arguments by unpacking them from the list. A set is a unique collection of unordered elements. The intersection operation creates a … Read more