Search code examples
pythonlistinequality

Python - Check if all elements in a list satisfy an inequality


I have a list T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]], and i want to check if all elements in each embedded list within T satisfy an inequality.

So far i have:

upper = 10
lower = 0
for n in range(len(T)):
    if all(lower < x < upper for x in T):
        'do something'
    else:
        'do something different'

So if all elements in each T[n] are between 0 and 10, i want to do something and if else then i want to do something else. In the list above T[0],T[1] and T[2] would satisfy the inequality whereas T[3] would not.


Solution

  • You are almost there. Just replace range(len(T)) with T to iterate over the T list and check for the nested elements in the if condition, as follows :

    >>> T = [[2,5],[4,7],[8,6],[34,74],[32,35],[24,7],[12,5],[0,34]]
    >>> upper = 10
    >>> lower = 0
    >>> for elem in T:
            if all(lower < x < upper for x in elem):
                print "True", elem
            else:
                print "False", elem
    
    
    True [2, 5]
    True [4, 7]
    True [8, 6]
    False [34, 74]
    False [32, 35]
    False [24, 7]
    False [12, 5]
    False [0, 34]