Results 1 to 6 of 6

Thread: Python Tuple Comparison Question

  1. #1
    Join Date
    Jul 2005
    Location
    Manitoba
    Beans
    118
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Python Tuple Comparison Question

    Hello everyone, I encountered something strange when trying to perform some tuple comparison while using python.

    In a python terminal I try and compare one tuple with another. I expect to get a boolean but I get another tuple? Here is what I enter:
    Code:
    >>> 1,1 == 1,1
    (1, True, 1)
    >>>
    However if I set the tuples as variables and compare them I get a boolean!
    Code:
    >>> a = 1,1
    >>> b = 1,1
    >>> a == b
    True
    >>>
    So I have away around the problem, but why was I getting that in the first place?

  2. #2
    Join Date
    Jun 2007
    Beans
    692

    Re: Python Tuple Comparison Question

    Precedence rules. 1, 1 == 1, 1 is evaluated as 1, (1 == 1), 1, which is why you get a tuple as a result. Also, the a = 1,1 assignment actually becomes (1, 1), which will be evaluated as you expect.
    Code:
    >>> a = 1,1
    >>> print a
    (1, 1)
    >>> b = (1,1)
    >>> print b
    (1, 1)
    >>> (1,1) == (1,1)
    True
    >>> 1, 1 == 1, 1
    (1, True, 1)
    >>> 1, (1 == 1), 1
    (1, True, 1)

  3. #3
    Join Date
    Mar 2008
    Beans
    4,714
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: Python Tuple Comparison Question

    Code:
    1,1==1,1
    is the same as

    Code:
    1,(1==1),1
    or
    Code:
    1,True,1

  4. #4
    Join Date
    Jun 2006
    Location
    CT, USA
    Beans
    5,267
    Distro
    Ubuntu 6.10 Edgy

    Re: Python Tuple Comparison Question

    Quote Originally Posted by Luggy View Post
    So I have away around the problem, but why was I getting that in the first place?
    because == has higher preference than comma?

    To make tuple, use (a,b,c). Comma just separates list arguments, () makes list into tuple.

    To make "one-ple" (tuple with just one item), canonical trick is (a,)

  5. #5
    Join Date
    Apr 2008
    Beans
    37
    Distro
    Ubuntu 7.10 Gutsy Gibbon

    Re: Python Tuple Comparison Question

    yup.. you need to be careful with variable assignments.. in the end it's just syntax.

  6. #6
    Join Date
    Jul 2005
    Location
    Manitoba
    Beans
    118
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: Python Tuple Comparison Question

    Awesome, thanks for the quick answer. I had a feeling it would be something simple like that.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •