× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Pythonic way to return interval from a list

Asad Saeeduddin
Oct 08, 2015
<p>I don't know about Pythonic, but here's a generator that will traverse the list only once and produce the middle values.</p> <pre><code>def get_between(names, first, last): f = l = False for n in names: l = l or n == last if f and not l: yield n f = f or n == first </code></pre> <p>It just takes the naive approach of remembering whether it has seen the first and last names you're interested in, and returning values when the the first has been seen but the last hasn't. You could probably add some early exiting to make it better.</p> <p>Here's a demo: <a href="http://ideone.com/ovnMX2" rel="nofollow">http://ideone.com/ovnMX2</a></p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30119578/Pythonic%20way%20to%20return%20interval%20from%20a%20list/30119958">Stack Overflow</a>.</p>
comments powered by Disqus