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.
To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.