Today's Python snippet is brought to you by the "in" keyword. In Python, we can use the in keyword for lots of different purposes. In terms of today's snippet, we're going to use it to check if a particular number is in a list.
To begin, let's say we have a list called coolNumbers. Take a look at the list below:
coolNumbers = [3, 1, 88, 7, 20, 95, 26, 7, 9, 34]
Now let's say we want to be able to identify if certain numbers are in the list. For example, maybe we want to know if 26 is in the list. Here's how we would do it, using the in keyword (make sure these lines of code appear in your Python files after you've already declared the list):
if 26 in coolNumbers: (print: "26 is a cool number")
That's literally all it takes to check if a number is in a list using the in keyword. It's very intuitive. If the number is found in the list, the phrase "26 is a cool number" will be printed. But what if the number you're looking for isn't in your list? Let's say you're looking for the number 29, and if it isn't already in the list, you'd like to add it to the list, because, as everyone knows, 29 is a very cool number. You can actually use the "not in" keyword to check if a number is not in the list. Combined with an if statement, you can check if the number in question is not in your list, and you can make sure it gets added if that's the case. Here's how you would do it:
if 29 not in coolNumbers: coolList.append(29)
That's all it takes. Not only is the process really simple, but, like a lot of Python code, it's very intuitive. Try it out for yourself by making your own list of cool numbers (include all the numbers that you think are cool) and seeing if you can identify and add your own integers.
Though using the "in" keyword is perhaps the most straightforward way, there are a few other ways to check whether a number is in a list in Python.
Checking if a Number is in a List with a for Loop
In Python, you can determine whether a number exists in a list by using a simple for loop. Let's break down a basic example:
- We first create a list containing some integers, which we'll call numbers_list.
- Next, we'll iterate (or loop) through each number in the list.
- We'll see if each number matches the number we're looking for, say target_num, using an if condition.
- We'll print a message confirming its existence if there's a match.
To illustrate, let's assume our list is [2, 5, 7, 8, 10, 4] and we're looking for the number 4:
# Creating the list numbers_list = [2, 5, 7, 8, 10, 4] # Searching for the number 4 in the list target_num = 4 for num in numbers_list: if num == target_num: print("Number Found!") break # Exit the loop as we've found the number |
The output is:
Number Found! |
Checking if a Number is in a List More than Once with the any() Function
Python offers the any() function to check certain conditions across list items easily. What's interesting is that we can use it to determine if there are any duplicate numbers within a list.
- We first set up a list named number_list containing various integers.
- Next, we use the any() function combined with a generator expression. This expression looks at each number in number_list and checks if it appears more than once.
- The outcome of this check is captured in the has_duplicates variable.
- We then display a message indicating the presence (or absence) of duplicate numbers in the list.
Let's look at the code for this example and use the list [2, 7, 8, 5, 7, 9]:
# Creating the list number_list = [2, 7, 8, 5, 7, 9] # Checking for duplicates using any() and a generator expression has_duplicates = any(number_list.count(item) > 1 for item in number_list) # Displaying the result print("Are there duplicate numbers in the list? : " + str(has_duplicates)) |
The output of this code is:
Are there duplicate numbers in the list? : True |
Checking if a Number is in a List with the count() Function
Python's count() method, inherent to lists, provides an efficient way to verify the existence of an element in the list. If the item is in the list, count() returns how often it appears. If this result is a non-zero positive number, then the element is present.
Let's see how this works with a practical example, using the list [12, 18, 25, 7, 50, 2900] and searching for the number 18:
# Setting up the list numbers_list = [12, 18, 25, 7, 50, 2900] print("Checking if 18 is in the list") # Counting the occurrences of the element in the list occurrences = numbers_list.count(18) # Verifying if the count is greater than 0 if occurrences: print("Yes, 18 is in the list") else: print("No, 18 isn't in the list") |
As you might have guessed, the output of this code is:
Checking if 18 is in the list
Yes, 18 is in the list
|
Checking if a Number is in a List with the find() Function
In this method, rather than searching the list directly, we convert the list's elements into strings and join them with hyphens. This creates a single, hyphen-separated string.
Next, we can use the find() function to check if the substring "15" is part of this string. If it locates "15", the script outputs "Yes, 15 is in the list"; otherwise, it conveys "No, 15 isn't in the list."
Let's see the code:
# Defining the list numbers_list = [11, 15, 23, 8, 48, 2910] print("Verifying if 15 is in the list") # Convert list numbers to strings string_list = list(map(str, numbers_list)) # Join list elements with hyphens joined_string = "-".join(string_list) # Using find() to check for the substring "15" if joined_string.find("15") != -1: print("Yes, 15 is in the list") else: print("No, 15 isn't in the list") |
The output is:
Verifying if 15 is in the list
Yes, 15 is in the list
|
But there's a catch for using this approach. It only works for lists with non-repeating and unique elements. However, if you had a number like 151 in the list in this example, the find() method will also detect the substring "15."
So, using this method can give you a false positive in certain scenarios.