2

Lets say there is a function return_list_from_iterable that takes any iterable as an argument.

def return_list_from_iterable(iterable):
    if is_finite(iterable): #check if iterator is finite
        return list(iterable)

Is there a way to check if iterator is fininite before calling list(iterable), e.g if to pass itertools.repeat('hello, infinity!') as an argument then, i guess, something bad can happen while the function is running.

pospolitaki
  • 313
  • 2
  • 9
  • 2
    nope, just `itertools.islice()` the number of elements you want/expect – Chris_Rands Jan 23 '20 at 12:36
  • Not an absolute dupe, but see [here](https://stackoverflow.com/questions/7460836/how-to-lengenerator) – CDJB Jan 23 '20 at 12:36
  • If it's a generator of any kind, you won't know until you iterate it to its end. Which is obviously nonsensical. For any non-iterator collection-y thing, you can check its `len()` if it has one. – deceze Jan 23 '20 at 12:39
  • 4
    You probably shouldn't be trying to turn iterators into lists if you have no idea about their finitude. – deceze Jan 23 '20 at 12:41
  • 2
    Heck, the answer to "is this iterator finite" might not even be well-defined until it terminates. Consider an iterator that makes decisions based on user input. – user2357112 Jan 23 '20 at 12:41
  • 1
    Checking for `len(x)` or `x.__length_hint__()` might be a start but will miss many cases – Chris_Rands Jan 23 '20 at 12:42
  • 1
    This is basically the Halting Problem, so no. – tzaman Jan 23 '20 at 13:35
  • Thanks you all, guys, for commenting, lot of useful stuff, you really helped! – pospolitaki Jan 23 '20 at 17:42

0 Answers0