深度阅读

How to check if an element is in a list in Python?

作者
作者
2023年08月22日
更新时间
11.6 分钟
阅读时间
0
阅读量

To check if an element is in a list in Python, you can use the in operator. The in operator returns a Boolean value (True or False) indicating whether the element is present in the list.

Here’s an example:

my_list = ['apple', 'banana', 'orange']
if 'banana' in my_list:
    print("Yes, 'banana' is in the list")
else:
    print("No, 'banana' is not in the list")

Output:

Yes, 'banana' is in the list

In this example, we define a list of fruits and then use the in operator to check if the element ‘banana’ is present in the list. Since ‘banana’ is indeed present in the list, the program prints “Yes, ‘banana’ is in the list”.

You can also negate the in operator to check if an element is not in a list:

my_list = ['apple', 'banana', 'orange']
if 'pear' not in my_list:
    print("No, 'pear' is not in the list")
else:
    print("Yes, 'pear' is in the list")

Output:

No, 'pear' is not in the list

In this example, we use the not in operator to check if the element ‘pear’ is not present in the list. Since ‘pear’ is not present in the list, the program prints “No, ‘pear’ is not in the list”.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。