How do I check if a tuple is present in a list in Python?

DDD
Release: 2024-10-27 12:35:02
Original
595 people have browsed it

How do I check if a tuple is present in a list in Python?

When checking for membership in a list in Python, elements that are not in the list evaluate to False, while elements that are in the list evaluate to True. This behavior applies to tuples as well.

In your code, the condition (curr_x-1, curr_y) not in myList is checking if the tuple (curr_x-1, curr_y) is not in the list myList. If the tuple is in the list, the condition will evaluate to False and the if statement will not execute. If the tuple is not in the list, the condition will evaluate to True and the if statement will execute.

Here's an example to illustrate the behavior:

<code class="python">myList = [(2, 3), (5, 6), (9, 1)]

if (2, 3) not in myList:
    print("The tuple (2, 3) is not in the list.")
else:
    print("The tuple (2, 3) is in the list.")</code>
Copy after login

The output of this code will be:

The tuple (2, 3) is in the list.
Copy after login

This is because the tuple (2, 3) is in the list myList, so the condition (2, 3) not in myList evaluates to False and the if statement does not execute.

If you want to execute the if statement only if the tuple is not in the list, you can simply change the condition to:

<code class="python">if (curr_x-1, curr_y) in myList:
    # Do something</code>
Copy after login

This will check if the tuple (curr_x-1, curr_y) is in the list myList. If it is, the if statement will execute. If it is not, the if statement will not execute.

The above is the detailed content of How do I check if a tuple is present in a list in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!