Search code examples
pythonlistequalsequivalent

Notation for equivalent items in a list in Python


I have two lists

circles_plotted = [1]
circles_next_plotted = [1]

Numbers are appended to list circles_plotted each time a circle is plotted. However, is the correct notation for and item in each of the lists to be equivalent? (this will be in an if statement):

(item in circles_next_plotted)==(item in circles_plotted)

Solution

  • The notation is incorrect.

    (item in circles_next_plotted)==(item in circles_plotted)
    

    is a NameError in Python:name 'item' is not defined.

    What you probably meant is

    >>> (item for item in circles_next_plotted)==(item for item in circles_plotted)
    False
    

    This is because (item for item in circles_next_plotted) is a generator expression and the two generators are two distinct objects, thus not equal.

    >>> (item for item in circles_next_plotted)
    <generator object <genexpr> at 0x000000D50AF46BF8>
    >>> (item for item in circles_plotted)    
    <generator object <genexpr> at 0x000000D50AF46CA8>
    

    To compare the lists you should use a simple comparison with the == operator which has been implemented for lists to do a per item comparison rather than a object identity check:

    >>> circles_next_plotted==circles_plotted
    True