# For loop in range python

Hi,
So I am trying to create a for loop that goes through a certain range, extracts all numbers one by one (n).
Each number that is extracted, it compares to x. so x=n and then checks if x returns a False or True.
Example:

``````x = range(1,5)
###go through range one by one, plug in x each time and check if output is False or True
``````

I thought of using a for loop or list comprehension but couldn’t get it to work.
Thanks for the help

what have you tried? You should go attempt the for loop, forget about list comprehension for now

You’re actually defining a list of numerals not a range. The assignment should be x = list(range(1,5))
This will create a list with the values 1, 2, 3, 4 .

To create a for loop that traverses the list the format is
for item in list:
statement 1 …

x will loop through 1,2,3,4, with each number being sent through the check_boolean() function. Then the loop appends the results to a list.

``````def check_boolean(x):
if x is True:
result = 'x is True.'
return result
elif x is False:
result = 'x is False.'
return result
else:
result = 'x is not boolean.'
return result

results=list()
for x in range(0,5):
result = check_boolean(x)
results.append(result)
print(results)
``````

An alternative might be to feed the function a list that contains boolean values:

``````results=list()
test = [True,False,True,False,True]
for x in range(0,5):
result = check_boolean(test[x])
results.append(result)
print(results)
``````

Just to clear a couple of things up before we close this thread…

In Python 2 (what these courses are based upon),

`range()` returns a list. Only Python 3 requires the list constructor since it returns an iterator, not a list.

What the OP (who is long gone, by the way) is (was) seeking was to do with equality, not whether the value is a boolean.

``````>>> def is_in_range(x):
return x in range(1, 5)

>>> is_in_range(4)
True
>>> is_in_range(6)
False
>>>
``````

The return value will be a boolean.

Recall that while there are only two member tokens in the `bool` class, there are infinitely many boolean expressions. We will want a function that can test them, as well.

``````>>> def is_boolean(x):
return isinstance(x, bool)

>>> is_boolean(7 > 6)
True
>>> is_boolean(is_in_range(5))
True
>>>
``````

@rumbold, please do not resurrect moribund topics (anything older than a week), especially when we cannot know if the OP is actively engaged or not.