# How to Compare List Elements to an Integer in Python?

Estimated read time 2 min read

To compare each element of a list to an integer in Python, you can use a loop or list comprehension to iterate over the list and perform the comparison. Here’s an example using a loop:

``````numbers = [10, 20, 30, 40, 50]
integer = 25

for num in numbers:
if num > integer:
print(num, "is greater than", integer)
elif num < integer:
print(num, "is less than", integer)
else:
print(num, "is equal to", integer)``````

In this example, we have a list called `numbers` and an integer called `integer`. The loop iterates over each element in the `numbers` list, and for each element, it compares it to the `integer`. Depending on the result of the comparison, it prints a corresponding message.

Alternatively, you can use a list comprehension to create a new list containing the comparison results:

``````numbers = [10, 20, 30, 40, 50]
integer = 25

comparison = ['greater than' if num > integer else 'less than' if num < integer else 'equal to' for num in numbers]
print(comparison)``````

In this example, we use a list comprehension to iterate over each element in the `numbers` list and create a new list called `comparison`. Each element in `comparison` represents the result of the comparison for the corresponding element in `numbers`.

You can modify the `numbers` list and the `integer` value in the examples above to perform the comparison with any other list and integer of your choice.

Add yours