# Python – Check if tuple list has all K

• Last Updated : 08 Jun, 2020

Sometimes, while working with Python records, we can have a problem in which we need to test if all the elements in tuples of tuple list are K. This problem can have application in many data domains such as Machine Learning and Web development. Let’s discuss certain ways in which this task can be performed.

Input : test_list = [(4, 4, 4, 4)], K = 4
Output : True

Input : test_list = [(7), (5, ), (5, ), (5, )], K = 5
Output : False

Method #1 : Using loop
This is brute force way in which this task can be performed. In this, we use loop to iterate each value in tuple and test if its K, if we find any element to be non-K, False is returned.

 `# Python3 code to demonstrate working of ``# Check if tuple list has all K``# Using loop`` ` `# initializing list``test_list ``=` `[(``4``, ``4``), (``4``, ``4``, ``4``), (``4``, ``4``), (``4``, ``4``, ``4``, ``4``), (``4``, )]`` ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# initializing K ``K ``=` `4`` ` `# Check if tuple list has all K``# Using loop``res ``=` `True``for` `tup ``in` `test_list:                  ``    ``for` `ele ``in` `tup:``        ``if` `ele !``=` `K:``            ``res ``=` `False`` ` `# printing result ``print``(``"Are all elements K ? : "` `+` `str``(res)) `

Output :

```The original list is : [(4, 4), (4, 4, 4), (4, 4), (4, 4, 4, 4), (4, )]
Are all elements K ? : True
```

Method #2 : Using `all() + any()`
This is yet another way in which this question can be answered. In this, we check for all elements to be K using all() and check if any of them doesn’t follow this behavior by using outer any().

 `# Python3 code to demonstrate working of ``# Check if tuple list has all K``# Using all() + any()`` ` `# initializing list``test_list ``=` `[(``4``, ``4``), (``4``, ``4``, ``4``), (``4``, ``4``), (``4``, ``4``, ``4``, ``4``), (``4``, )]`` ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# initializing K ``K ``=` `4`` ` `# Check if tuple list has all K``# Using all() + any()``res ``=` `any``(``all``(val ``=``=` `K ``for` `val ``in` `tup) ``for` `tup ``in` `test_list)`` ` `# printing result ``print``(``"Are all elements K ? : "` `+` `str``(res)) `

Output :

```The original list is : [(4, 4), (4, 4, 4), (4, 4), (4, 4, 4, 4), (4, )]
Are all elements K ? : True
```

My Personal Notes arrow_drop_up