7
Misusing Data Structures
Python has extremely well-designed data structures and data representations, many of which are discussed in the prior chapter. However, a few antipatterns, that are unfortunately common, can make the use of data structures dramatically inefficient or lead to unintended behavior in your code.
7.1 Quadratic Behavior of Repeated List Search
In Python, the in
keyword is a very flexible way of looking for “membership” in an object, most often some sort of container. Behind the scenes, the keyword in
is calling the .__contains__(self, elem)
method of the object that potentially has something “inside” it.
Bear with me for a few paragraphs while I discuss the behavior of in
, and before I get to the quadratic behavior gotcha ...
Get Better Python Code: A Guide for Aspiring Experts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.