Infinite for loop in Python like C++ - python

In C++ we can write an infinite for loop like for(;;). Is here any syntax like this to write an infinite for loop in Python?
Note : I know that if I write for i in range(a_very_big_value) then it may run infinity. I am searching a simple syntax like C++ or any other tricks to write infinite for loop in Python.

Python's for statement is a "for-each" loop (sort of like range-for in C++11 and later), not a C-style "for-computation" loop.
But notice that in C, for (;;) does the same thing as while (1). And Python's while loop is basically the same as C's with a few extra bells and whistles. And, in fact, the idiomatic way to loop forever is:1
while True:
If you really do want to write a for loop that goes forever, you need an iterable of infinite length. You can grab one out of the standard library:2
for _ in itertools.count():
… or write one yourself:
def forever():
while True:
yield None
for _ in forever():
But again, this isn't really that similar to for (;;), because it's a for-each loop.
1. while 1: used to be a common alternative. It's faster in older versions of Python, although not in current ones, and occasionally that mattered.
2. Of course the point of count isn't just going on forever, it's counting up numbers forever. For example, if enumerate didn't exist, you could write it as zip(itertools.count(), it).

Yes, it is possible.
With a while loop:
while True:
...
With a for loop (just for kicks):
from itertools import cycle
for _ in cycle(range(1)):
...
The cycle returns 1 indefinitely.
In either case, it's up to you to implement your loop logic in such a way that you terminate eventually. And lastly, if you want to implement an execute-until-___ loop, you should stick to while True, because that's the idiomatic way of doing it.

I found the answer from here and here
Using itertools.count:
import itertools
for i in itertools.count():
if there_is_a_reason_to_break(i):
break
In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes:
import sys
for i in xrange(sys.maxint):
if there_is_a_reason_to_break(i):
break
In Python3, range() can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it's probably best to use count()
It is also possible to achieve this by mutating the list you're iterating on, for example:
l = [1]
for x in l:
l.append(x + 1)
print(x)

Yes, here you are:
for i in __import__("itertools").count():
pass
The infinite iterator part was taken from this answer. If you really think about it though, a while loop looks way better.
while True:
pass

You can use:
while True:
# Do stuff here

for _ in iter(str, "forever"):
... pass
This may help. Because the iter() function creates an iterator that will call str() with no arguments for each call to its next() method[ This returns an empty string ]; if the value returned by str() is equal to the string "forever"(WHICH WILL NEVER HAPPEN AS "" != "forever"), StopIteration will be raised thus breaking the loop, otherwise the loop will continue running and this is the case for our loop.
REF: https://docs.python.org/3/library/functions.html?highlight=iter#iter

Related

Can you get all positive numbers in python?

So I am playing around in python and I thought:
"Is there a built in list or function that already has infinite numbers, if not how could I build one?"
I did some research and found...
Nothing
That is why I am here!
If you don't know what I mean it would be this but infinite:
b = [1,2,3,4,5,6,7,8,9]
etc;
If there is please tell me! Thank you!
Edit: Thank you!
You can define your own infinite list using a generator function without any module imports.
def infinite_list():
n = 1
while True:
yield n
n += 1
my_list = infinite_list()
Each time you want the next number call the next method:
next(my_list)
You can also iterate over it but it will, of course, be an infinite loop:
for elem in my_list:
//infinite loop
itertools.count produces an iterator over arbitrary, infinite numbers. It's not a sequence (you can't index it, you can only iterate each instance once), but you can keep going forever.
Actually running it to completion will take infinite time of course, so it's typically paired with something that limits it, e.g. itertools.islice, zip-ing with a finite iterable, etc.
from itertools import count
for i in count(1):
print(i)
its infinite though so it might take a while to run

python How to while loop while true , run multiple functions together

def function():
while True:
...omission...(this function is repeated permanently)
i =0
while i < 4:
driver.execute_script("""window.open("URL")""")
driver.switch_to.window(driver.window_handles[-1])
time.sleep(1)
function()
time.sleep(1)
i += 1 #open new tab and run function.
it doesn't work because while true loop is repeated permanently. Is there any ways to run multiple functions together?
https://imgur.com/a/4SIVekS This picture shows what I want
According to your picture, what you want is to launch the function a set number of times (4?), and run those in parrallel.
On a single core, as is the normal behavior, straight up parallel processing is impossible. You need to access other cores and manage a decentralized processing. while is useless there. I'm worried the level of difficulty is over your current skills, but here we go.
The overall flow that you (probably, depends on the actual memory safety of your functions) need is:
- to create a thread pool with the set number of threads for the number of runs you want.
- indicate the function you need to run
- start them, making sure the start itself is non-blocking.
- ensure one functions's processing doesn't impact another's results. race conditions are a common problem.
- gather results, again, in a non-blocking way.
You can use several methods. I highly recommend you read up a lot on the following documentations.
Threading:
https://docs.python.org/3/library/threading.html
Multiprocessing:
https://docs.python.org/3/library/multiprocessing.html
I don't understand your question because I don't understand what your function is supposed to do.
while True:
will always create an infinite loop. "while" is a command that tells python to loop through the following block so long as the expression following it evaluates to True. True always evaluates to True.
It seems like you want to use a conditional, like you do in "while x < 4".
x < 4
...is an expression that evaluates to true when x is less than 4, and false if x is not less than 4. Everything below the line:
while x < 4:
will then run if x is less than 4, and when it's done running that code, it will go back and evaluate if x is less than 4 again, and if it is, run the code again. To include another while loop inside of that loop, that new loop also needs an expression to evaluate. If you want to evaluate the same expression, write it out:
while x < 4:
# do something
while x < 4:
#do more things
# do even more things
# change x at some point, or else you're in an infinite loop.
However, there's no reason to do that specifically, because you're already doing it. All of the code is only running when x < 4, so checking that condition again right there is redundant, and doing it in another loop doesn't make sense. If the inside loop is also incrementing x, then the outside loop won't loop and doesn't need to increment x.
Also, if you want a function to check a condition based on a variable outside the function, you'll want to pass things to that function.

"Functions that consume an entire iterable won't terminate"?

In David Beazley's talk on generators, he states, as a caveat:
Functions that consume an entire iterable won't terminate(min, max,
sum, set etc.)
What is meant here?
gen = (x*2 for x in [1,2,3,4,5])
sum(gen) terminates just fine.
He's refering to that within the concept of infinite sequences, if you provide an infinite sequence to max et al, they simply won't be able to return a value.
Want to replicate? Aside from building a custom infinite sequence, Python has a built-in set of these in itertools (namely repeat, count, cycle). Try and do:
from itertools import repeat
max(repeat(20))
and see what happens. Actually, don't do that, max will keep on munching away as repeat keeps on giving numbers1. It's a love afair that lasts the challenge of time and never terminates :-)
1 -- Imagine Pac-Man in a never ending straight-line; constantly eating those little yellow thingies. Pac-Man = max, yellow thingies generated by repeat.
If you pay attention, you'll note that he writes that in Part 5 of the presentation, "Processing Infinite Data". Since infinite generators yield an infinite number of items, functions that attempt to consume the entire generator will never return.
An endless generator won't terminate when consumed:
def gen():
while True:
yield 1
sum(gen())
Note: Don't actually execute the last line.
In the provided document the comment is directed towards the follow function on page 39 which is designed to lock up the program until the file is added to, any infinite generator will not terminate when used with functions that use an iterable.
He is talking about infinite itertors many of which can be found in itertools for Python. If you use an infinite iterator with them they won't return.

How to bypass if checking after matching once in python?

Suppose i have below statement :
for i in range(10000):
if i==5:
do_something_for_5()
else:
do_something()
so you can see python need to check 10000 times whether i equals to 5, and 9999 of checking is wasted. my question is, is there any trick that after catching 5 once, python will bypass if-checking and go directly to exec do_something()? somewhat like short-circuit the whole if checking. How to do that?
More..
I don't think it is python problem, you see such checking pattern frequently in many languages.(compilers will optimize it?) The case is just for demo, I just hate to see the computer to check and check and check fruitless and just want to know the trick to avoid this. It likes such scenario: you know there is only one bad guy, and once you catch the bad guy, you withdraw the policemen and security checking to let others go directly, that will let process run faster.
More general code like this:
for member in member_list:
if time_consuming_inspect(member)==special_character:#known there is only one candidate match in advance
do_special_thing(member)
else:
do_common_thing(member)
Do a straightforward thing: break out of the loop after seeing 5, and run another loop to finish the work:
for i in range(10000):
if i==5:
do_something_for_5()
break
else:
do_something()
for i in range(i+1, 10000):
do_something()
One way would be to write something like this instead:
for i in range(4):
do_something()
do_something_for_5()
for i in range(6, 10000):
do_something()
If the special case for 5 need not be executed in order, then this will reduce duplication:
for i in itertools.chain(range(5), range(6, 10000)):
print i
It sounds like you really want something like self-modifying code so that it never does the check again, but I would advise against that. There isn't much impact for an extra check.
Response to comment
The following is not recommended and is overkill for this example, but it does work. It uses a different function after the check for 5 has succeeded. Keep in mind the function that the variable is assigned to must be looked up, so I doubt there will be a speed increase. This probably has very limited use, but nevertheless:
do_something = None
def do_something_with_check(i):
if i != 5:
print 'Doing something with check.'
else:
do_something_for_5()
global so_something
do_something = do_something_without_check
def do_something_without_check(i):
print 'Doing something without check.'
def do_something_for_5():
print 'Doing something for 5.'
do_something = do_something_with_check
for i in range(10):
do_something(i)
prints out:
Doing something with check.
Doing something with check.
Doing something with check.
Doing something with check.
Doing something with check.
Doing something for 5.
Doing something without check.
Doing something without check.
Doing something without check.
Doing something without check.
seenFive = False
for i in range(10000):
if not seenFive and i==5:
do_something_for_5()
seenFive = True
else:
do_something()
You could not iterate over 5, and perform that function separately:
nums = range(10000) # list(range(10000)) on python3
nums.remove(5) # Get rid of 5 from the list.
do_something_for_5()
for i in nums:
do_something()
I'm not sure this will help since the overhead of making the list might be more than checking if i==5 in each iteration.

for or while loop to do something n times [duplicate]

This question already has answers here:
More Pythonic Way to Run a Process X Times [closed]
(5 answers)
Closed 7 months ago.
In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:
for i in range(n):
do_sth()
And the other:
i = 0
while i < n:
do_sth()
i += 1
My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
So what do you think, which way is better?
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).
This is lighter weight than xrange (and the while loop) since it doesn't even need to create the int objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
python3 & python2
just use range():
for _ in range(n):
# do something n times exactly
The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for or while statement can have break, continue and else statements where:
break - terminates the loop
continue - moves on to the next time around the loop without executing following code this time around
else - is executed if the loop completed without any break statements being executed.
N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!

Categories

Resources