← Back to Blog

Is It in There?

The problem...

You have a value. You want to know if it exists somewhere.

Is this letter in the word? Is this word in the sentence?

You could check character by character. But that's slow, messy, and unnecessary.

The idea!

Python has a keyword that does exactly this in one word: in.

It checks if something exists inside something else. And it always returns a bool.

Making it real

message = "Hello Bull"

print("Bull" in message)    # True
print("Horn" in message)    # False

One line. One answer. True or False.

In practice

name = "RedHornDev"

print("Horn" in name)    # True
print("horn" in name)    # False — case sensitive
print("Red" in name)     # True
print("Dev" in name)     # True
print("dev" in name)     # False

in is case sensitive — exactly like everything else in Python.

not in

You can flip it with not:

message = "Hello Bull"

print("Horn" not in message)   # True — Horn is NOT in message
print("Bull" not in message)   # False — Bull IS in message

not in is the natural opposite of in.

Going further

You've already seen in with strings. But it works with other types too — you'll see that in the Data Structures chapter.

username = input("Enter your username: ")
banned = "admin"

print(banned in username)   # True if "admin" appears anywhere in the username

What's really happening

in searches through the sequence and returns True if it finds a match, False if it doesn't.

It's not magic — it's a check. And the result is always a bool.

Heads up!

  • in is case sensitive — "bull" and "Bull" are not the same
  • not in is two words — clean and readable
  • in works on strings now — and on lists and dicts later

The mindset shift

Stop thinking: "I need to write a loop to check if something exists."

Start thinking: "Python has in. One word. One answer."

What you should understand now

  • in checks if a value exists inside another value
  • It always returns a bool
  • not in is the opposite
  • in is case sensitive
[ login to bookmark ] // copied! 35 views · 1 min
// resources
Code Example in_operator.py
← prev What If One Thing Is True and the Other Isn't? next → Your Fourth Mini Project — Lock It Down
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.