For-loops with any() statements

Hi,

I need some Python examples that use for-loops with any() statements.

Something like

for any (some content here).

I haven’t found any explicit examples using for-loop in this way.

Any URLs and samples of PyCode, from basic to complex, are appreciated.

The any() function only returns True or False, so I can’t see that one would need to loop it: just pass an iterable to the function.

1 Like

If you’re talking about the Python builtin any() function, that’s not
how it is used. It returns a Boolean True result if any of the values
tested is true, otherwise False. Eg:

 has_a_prime = any( is_prime(n) for n in range(1000) )

Aside from expressing “any value is true” succinctly, it also has the
advantage of only running until it finds a true value. So the generator
expression above will only run until the first prime is encountered.

It isn’t clear what you mean by “for any (some content here)”. If you
mean, “for any values in the content matching some expression” one might
write:

 for p in [ n for n in range(1000) if is_prime(n) ]:
     print(p, "is prime")
     ... maybe do something with p ...

Can you describe what you’re seeking more clearly?

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Thanks. I’ve been trying to express the “infinity” concept. Then I ended up with a for-loop with an any() statement.

Since the float("+-inf") type is a tuple() and an int(). I haven’t found a way to use a for-loop to express infinity.

Your code makes sense to me.

For the concept of infinity: Here’s the best solution for me at the moment.

for infi in (n for n in range(-pow(2,3), pow(2,4))): # I can add more powers to it.

     print(infi, "is 'infinity'")

What do you think?

This isn’t working…Ugh

for p in (n for n in range (float('-inf'), float('inf'))):

     print(p, "is 'infinity'")

Iterating over a generator that iterates over an iterable?

That can be written much more simply as:

for infi in range(-pow(2, 3), pow(2, 4)):
     print(infi, "is 'infinity'")

When I went to school, none of the values in range(-8, 16) were called “infinity”.

No it isn’t. Its a float.

That’s because there isn’t one.

You can set up a loop that will run for a very long time, hours or days or years (assuming the power doesn’t go off) but that’s not going to help you. What is the point of writing a program that won’t give you the result that you want for fifty thousand years?

2 Likes

As you found out, the above will not work. But aside from that, for loops are designed for performing computations, rather than for expressing the concept of infinity. Among our choices of situations that merit a for loop, we can properly use one in order to iterate through a list that contains a finite number of items or through a range object that offers up a finite number of integers, upon demand.

However, if you are determined to express infinity by iterating through an infinite number of items, we can attempt to accommodate that need by offering an endless sequence of objects. How about a seemingly infinite flock of birds, such as crows? We can keep counting them until we get tired, or until we find another use for our computer.

Here is our infinite flock of crows:

# counting crows, seemingly infinite in number
def crow_counter():
    n = 1
    while True:
        yield n
        n += 1

crows = crow_counter()

No matter how many crows we count, there will always be a next one waiting to be counted.

print(next(crows))
print(next(crows))
print(next(crows))
print(next(crows))
...

Output:

1
2
3
4
....

Of course, if we would like to use a for loop, as you had requested, to iterate through an infinite number of items, such as our crows, we can do the following, instead of repeatedly using next(), but let’s be forewarned that it will be an infinite loop, which is something we generally try to avoid:

for crow in crows:
    print(crow)

You will need a different approach in order to express infinity.

It’s hard to make any sense out of this - loops don’t “express” concepts, and I can’t understand exactly what you’re expecting any to do, or how it’s supposed to help write the code.

Did you mean:

  • “I want a numeric value in my program that represents infinity” - that’s what float('inf') and float('-inf') are, and they are not integers nor tuples. They are, as the name float indicates, floating-point values.

  • “I want a value in my program that compares ‘greater than’ any other value, whether or not it’s numeric” - then make a class that represents that logic, and use an instance of that. Something like:

import functools

@functools.total_ordering
class Infinity:
    def __lt__(self, other):
        return False

infinity = Infinity()

Keep in mind that if instances of two different classes use the same logic, the one on the left-hand side of the comparison will “win”.

  • “I want a loop that will run forever (unless something else stops it)” - use while, not for:
while True:
    print('hi')
    # use ctrl-C to stop the code with a `KeyboardInterrupt`
  • “I want an object that represents an infinite sequence; something that can be looped over forever” - use the itertools standard module:
from itertools import count, repeat

for number in count():
    print(number) # will start at 0 and count up without limit until the loop is interrupted with ctrl-C

# or

for ayy in repeat('a'):
    print(ayy) # will be the letter a every time, and won't stop without ctrl-C
  • Something else? Please try to explain it more clearly.

Thanks. I’ve been trying to express the “infinity” concept.

If you’re after the concept of infinite, a for-loop isn’t going to be
much help. When we want a loop while runs forver we generally use a
while True: loop. Regardless of the flavour of loop, anything which
tries to “count to infinity” will never complete, and any intermediate
value in that counter eg in the unbounded sequence 1,2,3,4,… will not
be infinity.

Usually infinity (and things like the various types of infinite sets)
are treated symbolicly in maths, and thus also in programmes which deal
with in.

You might look at the sympy module, which facilitates doing symbolic
math in Python:
https://scipy-lectures.org/packages/sympy.html
https://docs.sympy.org/latest/install.html

It does come with an infinity symbol which is an object which compares
to be greater than other objects, etc.

Since the float("+-inf") type is a tuple() and an int().

This isn’t the case. It is a Python float, which a special IEEE754
floating point value used to indicate value in floating point
arithmetic.

Maybe you can provide some more detail about what you’re trying to do:

  • reason mathematically about infinity, which tends to be a symbolic
    operation
  • make loops which run forever, typically via while True:
  • make a sequence which is unbounded such as an unbounded iterator

For this last, you might imagine writing a loop like this:

 for n in cardinals():
     print(n)

which prints values for n starting at 1 and not stopping.

In this situation cardinals() returns an iterator which yields these
values as required. A Python for-loop does count, it just iterates over
whatever argument you give it. So:

 for i in [1,2,3]:

iterates over the elements in that 3 element list.

Here’s an unbounded cardinals() generator function:

 def cardinals():
     i = 1
     while True:
         yield i
         i += 1

This function, when you call it (as in the for-loop example above)
returns a generator which yields values when the for-loop iterator on
it, getting 1 then 2 etc. The generator is running the function
above, stalling when it yields a value. next time the for-loop
“iterates” by asking for the next value, the function resumes running
until it executes its next yield statement.

Cheers,
Cameron Simpson cs@cskk.id.au