Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Succinctly wrap a list in a callable that returns each list element in order for each successive call

I feel like I must be missing something obvious, but I can’t seem to find a succinct way of creating a a callable that returns elements of a list in order for each call. E.g.

In [1]: class CallableList: 
   ...:     def __init__(self, list_): 
   ...:         self.list = list_ 
   ...:         self.pos = -1 
   ...:     def __call__(self): 
   ...:         self.pos += 1 
   ...:         return self.list[self.pos] 
   ...:                                                                         

In [2]: x = CallableList([5, 7, 2])                                             

In [3]: x()                                                                     
Out[3]: 5

In [4]: x()                                                                     
Out[4]: 7

In [5]: x()                                                                     
Out[5]: 2

… but without a class.

A generator (which is where my mind first went) isn’t callable so that doesn’t seem to work, unless I’m missing something.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use iter() to obtain an iterator for a list. You can then use next() to obtain successive elements. For example:

>>> x = [1, 2, 3]
>>> r = iter(x)
>>> next(r)
1
>>> next(r)
2
>>> next(r)
3
>>> 

This is almost what you requested, but not quite, since you need to provide r as an argument to next.

To make a callable, you can can wrap it in a lambda:

>>> x = [1, 2, 3]
>>> r = iter(x)
>>> c = lambda: next(r)
>>> c()
1
>>> c()
2
>>> c()
3
>>> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading