Original: Https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_ Contained_in_a_list.html
Using the key in list to iterate the list will potentially cost n iterations to complete, and N is the key in the list position. If allowed, the list can be converted to set or dict, because Python finds elements in set or dict by directly accessing them without needing an iteration, which is much more efficient.
Anti-pattern
The following code defines a list type L, and then calls if 3 in L to check if 3 is in L. This is inefficient. This is followed by the fact that Python iterates through the list until it finds 3 or iterates through the list.
L = [1, 2, 3, 4]# iterates over three elements in the listif in L: Print("Thenumber 3 is in thelist. " Else: print("Thenumber 3 is not in thelist. ")
Recommended practice using Set or dict instead of list
The modified code is as follows and the list turns into set. More efficient behind this is because in Python, set attempts to directly access the target value rather than comparing each element in the iteration list with the target value.
s = Set ([1, 2, 3, 4])if in s: print("Thenumber 3 was in thel ist. " Else: print("Thenumber 3 is not in thelist. ")
Python performance: Do not use the key in list to determine if key is in the list