Why Doesn\'t \'not in\' Work as Expected with Tuples in Python?

Barbara Streisand
Release: 2024-10-30 09:20:03
Original
382 people have browsed it

Why Doesn't

Verifying Element Absence in a List Using Python

In Python, checking if an element is not present in a list can be achieved through the 'not in' operator. However, a common pitfall arises when working with lists of tuples.

Initial Code:

In the code provided:

if curr_x -1 > 0 and (curr_x-1 , curr_y) not in myList: 

    # Do Something
Copy after login

The programmer intends to execute the 'if' branch only if the specific tuple (curr_x-1, curr_y) is not in the myList. However, the code appears to malfunction.

Cause of the Issue:

The issue does not stem from the logical expression (curr_x-1 , curr_y) not in myList. This expression correctly evaluates to True if the tuple is absent from the list and False if it is present, as demonstrated in these examples:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True
Copy after login

Tuples vs. Lists:

The bug likely lies elsewhere in the code. Unlike with lists, tuples are immutable in Python. This means that once created, a tuple cannot be modified. If you attempt to modify it, a TypeError will be raised, which can disrupt the operation of the 'not in' operator.

Solution:

To avoid any potential issues, ensure that tuples in the list and the one you are checking for absence remain unchanged throughout the code. If they need to be modified, consider using lists instead of tuples.

The above is the detailed content of Why Doesn\'t \'not in\' Work as Expected with Tuples 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
Latest Articles by Author
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!