# Python – Paired Existence in Records

• Last Updated : 02 Jun, 2021

Sometimes, while working with Python records, we can have a problem in which we need to check for paired existence inside the record, or else if one doesn’t exist, other also should not. This kind of problem is common in domains such as Data Science and web development. Let’s discuss certain ways in which this task can be performed.

Input
test_list = [(‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘good’)]
pairs = (‘is’, ‘good’)
Output : [(‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘good’)]
Input
test_list = [(‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘better’)]
pairs = (‘better’, ‘good’)
Output : []

Method #1 : Using generator expression
This is brute force way in which this task can be performed. In this, we check for the existence/non-existence of both numbers and accept the result if, none or both are present.

## Python3

 `# Python3 code to demonstrate working of``# Paired Existence in Records``# Using generator expression` `# initializing list``test_list ``=` `[(``'Gfg'``, ``'is'``, ``'Best'``),``             ``(``'Gfg'``, ``'is'``, ``'good'``),``             ``(``'CS'``, ``'is'``, ``'good'``)]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# initializing Pairs``pairs ``=` `(``'Gfg'``, ``'Best'``)` `# Paired Existence in Records``# Using generator expression``res ``=` `[]``for` `sub ``in` `test_list:``    ``if` `((pairs[``0``] ``in` `sub ``and` `pairs[``1``] ``in` `sub) ``or` `(``         ``pairs[``0``] ``not` `in` `sub ``and` `pairs[``1``] ``not` `in` `sub)):``        ``res.append(sub)` `# printing result``print``(``"The resultant records : "` `+` `str``(res))`
Output :

The original list is : [(‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘good’), (‘CS’, ‘is’, ‘good’)]
The resultant records : [(‘Gfg’, ‘is’, ‘Best’), (‘CS’, ‘is’, ‘good’)]

Method #2 : Using XNOR
This is yet another way to solve this problem. In this, use the power of XOR operator to perform this task and negate the result.

## Python3

 `# Python3 code to demonstrate working of``# Paired Existence in Records``# Using XNOR` `# initializing list``test_list ``=` `[(``'Gfg'``, ``'is'``, ``'Best'``),``             ``(``'Gfg'``, ``'is'``, ``'good'``),``             ``(``'CS'``, ``'is'``, ``'good'``)]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# initializing Pairs``pairs ``=` `(``'Gfg'``, ``'Best'``)` `# Paired Existence in Records``# Using XNOR``res ``=` `[]``for` `sub ``in` `test_list:``    ``if` `(``not` `((pairs[``0``] ``in` `sub) ^ (pairs[``1``] ``in` `sub))):``        ``res.append(sub)` `# printing result``print``(``"The resultant records : "` `+` `str``(res))`
Output :
```The original list is : [('Gfg', 'is', 'Best'), ('Gfg', 'is', 'good'), ('CS', 'is', 'good')]
The resultant records : [('Gfg', 'is', 'Best'), ('CS', 'is', 'good')]```

My Personal Notes arrow_drop_up