0
good question
if we use 'in' in while loop it becomes a infinite loop but in for loop it becomes as length of list why??
1 Antwort
+ 5
In is a keyword used to check, whether a certain item exists in a list (or other similar objects) and it evaluates a boolean: true, if the searched item exists in the list, otherwise false.
Examples:
9 in [9, 4, 5] ---> True
2 in [1, 3, 4] ---> False
8 in [7, 8, 8] ---> True
Range objects work much like lists and you are also allowed to check whether an item exists in a range object:
9 in range(10) ---> True
10 in range(10) ---> False
1 in range(0, 10, 2) ---> False
And a similar boolean was evaluated by the while loop.
Using while loop:
while i in range(10):
print(i)
Would still result in error, because variable i isn't defined,
but I'm assuming you tried something like this:
for i in range(10):
print(i)
while i in range(10):
print(i)
Where i was defined by the for loop and i ended up with value 9, which you used in the while loop expression and which would equal:
while 9 in range(10):
print(i)
and because 9 in range(10) is always True, the loop became infinite.