when you use while True: the code inside it will run forever until you break
so in your code, I think you need to do this:
test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
for i in test_list:
if not i in alert:
print('exists')
alert.append(i)
EDIT: if you want to run it forever:
test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
while True:
for i in test_list:
if not i in alert:
print('exists')
alert.append(i)
Answer from Mhmd Admn on Stack OverflowVideos
when you use while True: the code inside it will run forever until you break
so in your code, I think you need to do this:
test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
for i in test_list:
if not i in alert:
print('exists')
alert.append(i)
EDIT: if you want to run it forever:
test_list = [ 1, 6, 3, 5, 3, 4 ]
alert = []
while True:
for i in test_list:
if not i in alert:
print('exists')
alert.append(i)
add a break statement after alert.append(i), since the condition is met you need to exit the loop. Your loop is set to true thus you need to use break to exit the loop. You'll also iterate through the list an infinite amount of times if the condition is never met. You should try using a for loop to iterate through the list one time at most.
if i in test_list and (i != alert):
print('exists')
alert.append(i)
break
You don't need a list comprehension for that. range will do:
x = list(range(5, 21, 10)) # [5, 15]
A while loop is not possible inside of a list comprehension. Instead, you could do something like this:
def your_while_generator():
i = 5
while i <= 20:
yield i
i += 10
[i for i in your_while_generator()]
No, you cannot use while in a list comprehension.
From the grammar specification of Python, only the following atomic expressions are allowed:
atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
The expression corresponding to a list comprehension - testlist_comp looks like the following in Python 3:
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
Here, the only statements allowed are
test: or_test ['if' or_test 'else' test] | lambdef
star_expr: '*' expr
comp_for: [ASYNC] 'for' exprlist 'in' or_test [comp_iter]
where
comp_if: 'if' test_nocond [comp_iter]
comp_iter: comp_for | comp_if
There is not a single while statement allowed anywhere. The only keywords you are allowed to use is a for, for a for loop.
Solution
Use a for loop, or take advantage of itertools.
what you are looking for is:
for i, elem in enumerate(foo):
#i will equal the index
#elem will be the element in foo at that index
#etc...
the enumerate built-in takes some sequence (like a list, or a generator), and yields a tuple, the first element of which contains the iteration number, and the second element of which contains the value of the sequence for that iteration.
Since you specifically ask about an "unknown number of indexes", I also want to clarify by adding that enumerate works lazily. Unlike len, which needs to calculate/evaluate an entire sequence in advance (assuming that you are working with something more complicated than a simple list), and would thus fail for an infinite list, and take an indeterminate amount of time for some arbitrary generator function (which would then need to be run again, possibly leading to side effects), enumerate only evaluates the next sequence in the list. This can be shown using the fact that it will perform as expected on the easiest to make example of a sequence with an unknown number of entries: an infinite list:
import itertools
for i, elem in enumerate(itertools.cycle('abc')):
#This will generate -
# i = 0, elem = 'a'
# i = 1, elem = 'b'
# i = 2, elem = 'c'
# i = 3, elem = 'a'
# and so on, without causing any problems.
EDIT - in response to your comments:
Using for ... enumerate ... is inherently more expensive than just using for (given that you have the overhead of doing an additional enumerate). However, I would argue that if you are tracking the indexes of your sequence elements, that this tiny bit of overhead would be a small price to pay for the very pythonic presentation it affords (that is to say, i=0; i += 1 is a very C-style idiom).
After doing a little bit of searching, I dug up (and then agf corrected the url for) the source code for the enumerate function (and additionally, the reversed function). It's pretty simple to follow, and it doesn't look very expensive at all.
if you have a python list, you can iterate through the list with a for loop:
for i in list
if you have to use the while loop, you can try
i=0
while i<len(foo):
...
i+=1
I was going through the "Python Crash Course" book by Eric Matthes, and in a chapter dedicated to "User Input and While Loops" read the following:
A for loop is effective for looping through a list, but you shouldn’t modify a list inside a for loop because Python will have trouble keeping track of the items in the list. To modify a list as you work through it, use a while loop
Is there any benefit on using a while loop to traverse a list instead of a for loop? Other than the while loop "knows" if there are any elements remaining in said list. Oh, forgot to mention, the examples involve moving items from one list to another, until the first one is empty.
Also, what is your opinion about this book? I have found it amazing so far, and the fact it includes a couple of full-fledged projects motivates me to go thorugh it and research about any concept I may not feel comfortable with.