If you want to return the elements that are in one of the lists but not in the other you can use the method symmetric_difference()
or ^
.
a = ['Manzana','Peras','Bananas']
b = ['Manzana','Peras']
print(set(a).symmetric_difference(set(b)))
Return us:
{'Bananas'}
Another example:
a = ['A', 'Y', 'C', 'B', 'L']'
b = ['Y', 'C', 'U', 'L']
print(set(a) ^ set(b))
Return us:
{'B', 'U', 'A'}
If you use the difference()
or -
method returns only the elements that are in the first list but not in the second one :
a = ['A', 'Y', 'C', 'B', 'L']'
b = ['Y', 'C', 'U', 'L']
print(set(a) - set(b))
Return us:
{'B', 'A'}
As you see, both should be set()
Some data is missing such as which database you use, how you store and extract that data from the database, etc ... For these methods to work, you have to be able to transform the data into a set ( set()
).
On the other hand list(set(queryUno[0]) - set(queryDos[0]))
creates an object (a list) that contains the difference between the two sets but it will not print anything, you would need to do something like:
print(list(set(queryUno[0]) - set(queryDos[0])))
Update including example using sqlite3
:
I will create a database locally (called datos.db
) with two tables called stock1
and stock2
. Each table has 3 columns that are fruta
, kilogramos
and cajas
. The objective is to compare the two tables using the column frutas
and print those fruits that are in stocks1
and not in stocks2
:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
#Creamos una base de datos llamada datos.db
con = sqlite3.connect('datos.db')
cursor = con.cursor()
#Creamos una tabla llamada stock1 y añadimos 3 filas
cursor.execute('''CREATE TABLE stocks1 (fruta, kilogramos, cajas)''')
items = [('Manzanas','12','4'), ('Peras','10','2'),('Bananas','5','1')]
cursor.executemany('INSERT INTO stocks1 VALUES (?,?,?)', items)
#Creamos una tabla llamada stock1 y añadimos 2 filas
cursor.execute('''CREATE TABLE stocks2 (fruta, kilogramos, cajas)''')
items = [('Manzanas','12','4'), ('Peras','10','2')]
cursor.executemany('INSERT INTO stocks2 VALUES (?,?,?)', items)
con.commit()
con.close()
#Accedemos a nuestra base de datos
con = sqlite3.connect('datos.db');
cursor = con.cursor()
#Extraemos el primer elemento de cada fila de la tabla stocks1
##y lo almacenamos en la lista queryUno
cursor.execute("SELECT * FROM stocks1")
queryUno = set(row[0] for row in cursor)
#Extraemos el primer elemento de cada fila de la tabla stocks2
##y lo almacenamos en la lista queryDos
cursor.execute("SELECT * FROM stocks2")
queryDos = set(row[0] for row in cursor)
#Comparamos las dos tablas
print(queryUno - queryDos)
con.close()
This prints us:
>>> ['Bananas']
Greetings.