Comparing tuple values

python compare tuples in list
python tuple
python tuple assignment
tuple get value
tuple key value pair python
get first value of tuple python
python3 compare tuple
tuple tutorialspoint

I'm quite new to Python/Flask and am writing a little script for some home automation I'm playing with.

At the moment, there's a route in my script that gets run by a cron job. This sniffs for bluetooth packets to see who's in and who's out of the house so I can control the heating. There's a row in my table for each person and a status which is either In or Out.

This works perfectly.

I've got another route to read the values back and display either a green or red bar on my dashboard depending on if they're in or out.

It's reading the values and doing some logic that I'm having problems with.

If I get the status for a person and display it on my dashboard (created with an HTML template), the value it displays is:

('In',)

In the MySQL table it's just In - no quotes or parentheses.

In my Python script I have:

conn = MySQLdb.connect(host="localhost", user = "*****", passwd = "*****", db = "mydb")
                cursor = conn.cursor()
                cursor.execute("select status from occupants WHERE id = '1'")
                data = cursor.fetchone()
                result = data
                #result = str(result)
                if (result == "In"):
                   result = "In"
                else:
                  result = "Out"

This always returns Out.

I've tried various things in my if statement but I obviously haven't hit the right one. I've even tried:

if (result == "('In',)")

But even this returns Out.

Starting to tear my hair out now as I've been searching and playing for about 2 days just on this.

Any ideas gratefully received!

You need to get the value by index. Python returns tuples for the rows.You need to get the first column.

Just get the value by index, data[0]

Then you go on with comparison.

Edit: when you use the "in" operators, you are just looping through the tuple.

It works buts not a good idea, when you already know for sure, the data you are looking for is at index 0.

How does tuple comparison work in Python?, In packing, we place value into a new tuple while in unpacking we extract those values back into variables. x = ("Guru99", 20, "Education") # tuple  Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements.

You are using cursor.fetchone(), which returns a tuple or None(if element not found). So what you are receiving after executing the command is a tuple with only one element, which makes lesser sense in this context, but that is how this Python API returns data. So even after using fetchone() you need to access the first element explicitly, which can be done as lst[0]. So you need to change the line as:

result = ""
if data is not None: 
    result = data[0]
print result

Patterns, In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every  You can also compare the instance of two value tuples with each other by using CompareTo(ValueTuple<T1, T2>) method. Or in other words, with the help of CompareTo method you are allowed to compare the current ValueTuple<T1, T2> instance to a specified ValueTuple<T1, T2> instance. This method also compares nested value tuples with each other.

You have more Data in "result" then just "In". For example:

a = ["yes", "hello"]
b = "no"

if "yes" == a:
    print("yes yes yes")
else:
    print("Something is wrong")

This gives you "Something is wrong" as output, but if you do:

a = ["yes", "hello"]
b = "no"

if "yes" in a:
    print("yes yes yes")
else:
    print("Something is wrong")

Now you get "yes yes yes" as output. Hope this helps a bit :)

Python Tuples and Tuple Methods - Michael Galarnyk, , else the second item is considered, then the third and so on. Comparing tuples. A comparison operator in Python can work with tuples. The comparison starts with a first element of each tuple. If they do not compare to =,< or > then it proceed to the second element and so on. It starts with comparing the first element from each of the tuples

How to split Python tuples into sub-tuples?, with values can be initialized by making a sequence of values separated by commas. If numbers, perform numeric coercion if necessary and compare. If either element is a number, then the other element is "larger" (numbers are "smallest"). Otherwise, types are sorted alphabetically by name. If we reached the end of one of the tuples, the longer tuple is "larger."

Ok, as always, 5 minutes after posting, I try something different and get it working. However, I'm not sure if this is a fudge or if it's a valid thing to do:

if 'In' in result:

This now works.

For the purposes of this exercise, it doesn't really matter if it's a dirty workround but I'd like to know if there's a more elegant/conventional solution just for my learning.

In this, we just compare all elements using all() . The cross tuple access is done by zip() and generator expression gives us the logic to compare. filter_none. edit You can compare two tuples by using equality == and != operators. The process compares left side of the tuple members with the right side of the tuple members in order. The == operator stops evaluating once it finds that member of the left side does not match with the member on the right side.

!= , in , not in ) work exactly the same among tuple s as they do among string s. The tuple s are compared element by element. If the corresponding elements are​  The following example calls the Tuple<T1,T2>.Equals(Object) method to determine whether any of the objects in an array of Tuple<T1,T2> objects are equal to one another. The output reflects the fact that the Equals(Object) method returns true when comparing Tuple<T1,T2> objects whose components have equal values.

Return Value. If elements are of the same type, perform the compare and return the result. If elements are different types, check to see if they are numbers. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries. Syntactically, a tuple is a comma-separated list of values: >>> t = 'a', 'b', 'c', 'd', 'e'

Tuples are compared position by position: the first item of the first tuple is compared to Sets will take the tuples and take only unique values. C# tuple types. 05/15/2018; 20 minutes to read +12; In this article. C# tuples are types that you define using a lightweight syntax. The advantages include a simpler syntax, rules for conversions based on number (referred to as cardinality) and types of elements, and consistent rules for copies, equality tests, and assignments.

Comments
  • I had that originally and changed my query to fetchone instead of fetchall. In both cases, even without the index, it still read the correct value from the table. Thank you for your help, though. For the moment, I'll probably stick with "in".
  • You should always try to write optimized code, it will help you in long run. Just my advice.
  • Thank you! I'll give that a try a bit later. It's doing what I need for the moment and I'm impatient to get to grips with the API for the thermostat to turn the heating off if the house is empty :)
  • Thank you. That's an interesting one but makes sense to me with the tiny, tiny bit of work I've done trying to extract values from JSON.