Python Less Than or Equal To (<=) Operator
Python Less Than or Equal To Operator
Python Less Than or Equal To operator is used to compare if an operand is less than or equal to other operand.
Syntax
The syntax of less than or equal to comparison operator is
operand_1 <= operand_2
Less than or Equal to operator returns a boolean value. True if operand_1 is less than or equal to operand_2 in value. Otherwise, it returns False. If the operands are sequences like strings, lists, tuple, etc., corresponding elements of the objects are compared to compute the result.
For sequences, the comparison happens for all the respective elements from two sequences, until they get False from a comparison or the end of a sequence is reached with all Trues returned during comparisons.
Less than or Equal to can be considered as a compound expression formed by Less than operator and Equal to operator as shown below.
(operand_1 < operand_2) or (operand_1 == operand_2)
Example 1
In this example, we will compare two integers, x and y, and check if x is less than or equal to y.
Python Program
x = 5
y = 12
result = x <= y
print(result) #True
x = 8
y = 8
result = x <= y
print(result) #True
x = 78
y = 8
result = x <= y
print(result) #False
Output
True
True
False
Example 2: Less than or Equal to Operator with Sequences
Sequence could be a string, a list, a tuple, etc. You can compare two sequences using less than or equal to comparison operator.
For numbers, it is straight forward mathematical decision if the left operand is less than or equal to the right operand. But for sequences, the operator iteratively compares the respective elements from the two sequences. The comparison happens for all the respective elements from two sequences, until they get False from a comparison or the end of a sequence is reached with all Trues returned during comparisons.
In the following program, we will compare two lists, x and y, and check if x is less than or equal to y.
Python Program
x = [41, 54, 21]
y = [98, 8]
z = [41, 54, 4, 6]
k = [41, 54, 21]
print(x <= y) #True
print(x <= z) #False
print(x <= k) #True
Output
True
False
True
Checking x <= y
means checking if [41, 54, 21] <= [98, 8]
. During the comparison of first element in the lists, less than or equal to operator returns True.
For x <= z
means checking if [41, 54, 21] <= [41, 54, 4, 6]
. During the comparison of first two element in the lists, less than or equal to operator returns True. So, the operator investigates until it reaches the end of a list with True for all the elements, or a False in the mid way. For the third element, the operator returns False. The operator now stops the comparison and returns False.
And for x <= k
, from the data, it is straight forward that the operator returns True.
Summary
In this tutorial of Python Examples, we have learned about Less than or Equal to Comparison Operator.