杰瑞科技汇

Python如何判断元素不在列表中?

Of course! The not in operator in Python is a fundamental and highly useful tool for checking if an item is absent from a list (or any other iterable, like tuples, strings, etc.).

Python如何判断元素不在列表中?-图1
(图片来源网络,侵删)

Here’s a complete guide covering its syntax, usage, and common scenarios.

Basic Syntax

The syntax is very straightforward and reads like English:

item not in list_name

This expression evaluates to a boolean value:

  • True if the item is not found in the list_name.
  • False if the item is found in the list_name.

Simple Examples

Let's start with a basic list of fruits.

Python如何判断元素不在列表中?-图2
(图片来源网络,侵删)
fruits = ['apple', 'banana', 'cherry', 'mango']
# Check if an item is NOT in the list
print('grape' not in fruits)  # Output: True (because 'grape' is not in the list)
print('apple' not in fruits) # Output: False (because 'apple' IS in the list)

You can also use it directly inside an if statement to control the flow of your program.

fruits = ['apple', 'banana', 'cherry', 'mango']
fruit_to_check = 'grape'
if fruit_to_check not in fruits:
    print(f"Sorry, we don't have {fruit_to_check} in stock.")
else:
    print(f"Great news! We have {fruit_to_check} in stock.")
# --- Output ---
# Sorry, we don't have grape in stock.

Common Use Cases

a) Input Validation

This is one of the most common uses. You can check if a user's input is valid before proceeding.

valid_colors = ['red', 'green', 'blue', 'yellow']
user_color = input("Enter a color: ")
if user_color.lower() not in valid_colors:
    print("Invalid color. Please choose from red, green, blue, or yellow.")
else:
    print(f"You chose {user_color}. That's a valid color.")
# Example 1:
# Enter a color: purple
# Invalid color. Please choose from red, green, blue, or yellow.
# Example 2:
# Enter a color: Red
# You chose Red. That's a valid color.

b) Conditional Logic

You can use not in to execute a block of code only if a certain condition is not met.

allowed_users = ['admin', 'manager', 'editor']
current_user = 'guest'
if current_user not in allowed_users:
    print("Access Denied. You do not have permission.")
else:
    print("Access Granted. Welcome!")
# --- Output ---
# Access Denied. You do not have permission.

c) Checking for an Empty List (Indirectly)

While if my_list: is the most direct way to check for an empty list, not in can be used to check if a specific placeholder value is absent.

Python如何判断元素不在列表中?-图3
(图片来源网络,侵删)
shopping_cart = []
# The list is empty, so 'milk' is definitely not in it.
if 'milk' not in shopping_cart:
    print("You haven't added milk to your cart.")
# --- Output ---
# You haven't added milk to your cart.

not in with Other Data Types

The not in operator is not limited to lists. It works with any iterable.

a) Tuples

coordinates = (10.0, 20.0, 30.0)
print(15.0 not in coordinates) # Output: True
print(20.0 not in coordinates) # Output: False

b) Strings

When used with a string, not in checks for the absence of a substring.

message = "Hello, world!"
print('world' not in message)    # Output: False (because 'world' is a substring)
print('goodbye' not in message)  # Output: True
print('H' not in message)       # Output: False

c) Dictionaries

When used with a dictionary, not in checks for the absence of a key by default.

user_profile = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print('email' not in user_profile)  # Output: True (the 'email' key does not exist)
print('name' not in user_profile)   # Output: False (the 'name' key exists)

Performance: How Does not in Work?

It's important to understand that Python searches through the list one item at a time. This is called a linear search.

  • Time Complexity: O(n), where 'n' is the number of items in the list.
  • This means the time it takes to check grows linearly with the size of the list.

Implication: For very large lists, using not in repeatedly can be slow.

# This can be slow if `big_list` has millions of items
if 'some_value' not in big_list:
    # do something

When to be careful: If you need to check for the presence/absence of items many times in a large collection, a set is a much better choice. Sets provide an average time complexity of O(1) for lookups, meaning the search time is constant and doesn't depend on the size of the set.

# Create a set from your list for fast lookups
big_set = set(big_list)
# This is extremely fast, even for millions of items
if 'some_value' not in big_set:
    # do something

Summary Table

Expression Meaning Returns True when...
item in list Item is present The item exists in the list.
item not in list Item is absent The item does not exist in the list.

In short, not in is your go-to operator for checking for the absence of an item in a list or any other iterable in Python. It's readable, efficient for most common use cases, and a fundamental part of writing clean Python code.

分享:
扫描分享到社交APP
上一篇
下一篇