In this tutorial, you’ll learn how to use Python to check if a list contains an item. Put differently, you’ll learn if an item exists in a Python list. Being able to determine if a Python list contains a particular item is an important skill when you’re putting together conditional expressions. For example, if you’re developing a web application, you may want to see if a user has already selected a number of values. Otherwise, if you’re developing a game, you may want to see if a user has different items in their inventory. Show By the end of having read this tutorial, you’ll have learned how to check for membership in a list. You’ll learn how to do this using the in keyword, as well as checking if an item doesn’t exist in a Python list using the not in keywords. You’ll also learned how to check if a list contain an item using the Python any() function, as well as the count() function. Finally, you’ll learn some naive implementations of checking membership in a list, such as for-loops and list comprehensions. The Quick Answer: Use in To Check if a Python List Contains an Item Check if a Python list contains an itemCheck if a Python List Contains an Item Using inOne of the easiest and most Pythonic ways to check for membership in a Python list is to use the in key. Technically, the in keyword serves two purposes:
In this case, we’ll use the in keyword to check if an item exists in a list. This provides a readable and almost plain-English way to check for membership. Let’s see what this looks like: # Check if a Python List Contains an Item items = ['datagy', 'apples', 'bananas'] if 'datagy' in items: print('Item exists!') # Returns: Item existsWe can that by writing if 'item' in items, we’re able to evaluate if something exists in our list. This is a really intuitive way to check if items exist or not. In the next section, you’ll learn how to use Python to check if an item doesn’t exist. Need to replace an item in a list? Check out my tutorial on this topic here: Python: Replace Item in List (6 Different Ways) Check if a Python List Doesn’t Contain an Item Using not inIn this section, you’ll learn to check if a list doesn’t contain an item. We can do this by negating the in keyword, using the not keyword. Similar to the example above, this reads like relatively plain English. Let’s see how we can use the not in keyword to see if an item isn’t a list: # Check if a Python List Doesn't Contain an Item items = ['datagy', 'apples', 'bananas'] if 'oranges' not in items: print("Item doesn't exists!") # Returns: Item doesn't exist!We can see that the not in keyword allows us to determine if an item doesn’t exist. It returns the opposite truthiness of the in keyword. Because of this, it allows us to write cleaner code. In the next section, you’ll learn to check for membership in a Python list using the .count() method. Need to remove an item for a list? Check out my tutorial to learn how to here: Remove an Item from a Python List (pop, remove, del, clear) Check if a Python List Contains an Item Using countPython lists come with a number of different helpful methods. One of these methods is the .count() method, which counts the number of times an item appears in a list. Because of this, we can see if an item exists in a list if the count of that item is anything greater than 0. If the count is 0, then the item doesn’t exist in our list. Let’s see what this looks like: # Check if a Python List Contains an Item using .count() items = ['datagy', 'apples', 'bananas'] if items.count('datagy') > 0: print('Item exists!') # Returns: Item exists!If any item exists, the count will always be greater than 0. If it doesn’t, the count will always be 0. We can combine this if statement into a single line as well. Let’s see what this looks like: # Check if a Python List Contains an Item using .count() items = ['datagy', 'apples', 'bananas'] print('Exists') if items.count('datagy') else print("Doesn't exist") # Returns: ExistsThe expression here works like the Python ternary operator. If you want to learn more about how the Python ternary operator works, check out my in-depth guide on the ternary operator here. In the next section, you’ll learn how to use the any() function to check for membership in a Python list. Want to learn how to shuffle a list? Check out my tutorial here: Python: Shuffle a List (Randomize Python List Elements) Check if a Python List Contains an Item Using anyThe Python any function scans an iterable and returns True if any of the items in the iterable are True. So, how can we use the any function to check for membership in a Python list? We can place a comprehension inside the any function to check for membership. If any item is returned, the any function will return True. Let’s see what this looks like and then dive into how this works: # Check if a Python List Contains an Item using any() items = ['datagy', 'apples', 'bananas'] print(any(item=='datagy' for item in items)) # Returns: TrueThe way that this works is that the comprehension will loop over each item in the list and check if the item is equal to the one we want to check for. If it is, the comprehension returns True for that item. Otherwise, it’ll return False. Because of this, if a True value exists, the any function will return True. In the next section, you’ll learn how to use a for loop to check if an item exists in a list. Want to learn how to check the length of a Python list? Learn all you need to know with this tutorial that covers five different ways to check the length: Python List Length or Size: 5 Ways to Get Length of List Check if a Python List Contains an Item Using a For LoopIn this final section, you’ll learn how to use a for loop to check for membership in a list. We can loop over each item in our list and see if the item matches we want to check. Once the item is found, the for loop sets a value to True and the for loop breaks. Let’s see what this looks like in Python: # Check if a Python List Contains an Item using a for loop items = ['datagy', 'apples', 'bananas'] exists = False for item in items: if item == 'datagy': exists = True break print(exists) # Returns: TrueLet’s break down what we did here:
Need to remove duplicate items from a Python list? This tutorial will teach you seven different ways to do this: Python: Remove Duplicates From a List (7 Ways) ConclusionIn this tutorial, you learned how to check for membership in a Python list, meaning checking whether an item exists. You learned how to do this using the in keyword. You then learned how to check whether an item doesn’t exist, using the not in keyword. You then learned other methods to check for membership, using the any function, the .count method, and a Python for loop. To learn more about the Python in keyword, check out the official documentation here. The official documentation for the any function can be found here and for the .count method, it can be found here.
The original question was:
Thus there are two things to find:
Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method. Results Methods are:
Results show that method 5 is the fastest. Interestingly the try and the set methods are equivalent in time. Test Code import random import bisect import matplotlib.pyplot as plt import math import timeit import itertools def wrapper(func, *args, **kwargs): " Use to produced 0 argument function for call it" # Reference https://www.pythoncentral.io/time-a-python-function/ def wrapped(): return func(*args, **kwargs) return wrapped def method_in(a,b,c): for i,x in enumerate(a): if x in b: c[i] = b.index(x) else: c[i] = -1 return c def method_try(a,b,c): for i, x in enumerate(a): try: c[i] = b.index(x) except ValueError: c[i] = -1 def method_set_in(a,b,c): s = set(b) for i,x in enumerate(a): if x in s: c[i] = b.index(x) else: c[i] = -1 return c def method_bisect(a,b,c): " Finds indexes using bisection " # Create a sorted b with its index bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0]) for i,x in enumerate(a): index = bisect.bisect_left(bsorted,(x, )) c[i] = -1 if index < len(a): if x == bsorted[index][0]: c[i] = bsorted[index][1] # index in the b array return c def method_reverse_lookup(a, b, c): reverse_lookup = {x:i for i, x in enumerate(b)} for i, x in enumerate(a): c[i] = reverse_lookup.get(x, -1) return c def profile(): Nls = [x for x in range(1000,20000,1000)] number_iterations = 10 methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup] time_methods = [[] for _ in range(len(methods))] for N in Nls: a = [x for x in range(0,N)] random.shuffle(a) b = [x for x in range(0,N)] random.shuffle(b) c = [0 for x in range(0,N)] for i, func in enumerate(methods): wrapped = wrapper(func, a, b, c) time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations))) markers = itertools.cycle(('o', '+', '.', '>', '2')) colors = itertools.cycle(('r', 'b', 'g', 'y', 'c')) labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse')) for i in range(len(time_methods)): plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels)) plt.xlabel('list size', fontsize=18) plt.ylabel('log(time)', fontsize=18) plt.legend(loc = 'upper left') plt.show() profile() |