Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7879585
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T03:55:47+00:00 2026-06-03T03:55:47+00:00

A common pattern in my code is: search through a list until I find

  • 0

A common pattern in my code is: “search through a list until I find a particular element, then look at the elements that come before and after it.”

As an example, I might want to look through a log file where important events are marked with asterisks, and then pull out the context of the important event.

In the following example, I want to know why the hyperdrive exploded:

  Spinning up the hyperdrive
  Hyperdrive speed 100 rpm
  Hyperdrive speed 200 rpm
  Hyperdrive lubricant levels low (100 gal.)
* CRITICAL EXISTENCE FAILURE
  Hyperdrive exploded

I want a function, get_item_with_context(), that allows me to find the first line with an asterisk, and then gives me up to n lines preceding it, and m lines following it.

My attempt is below:

import collections, itertools
def get_item_with_context(predicate, iterable, items_before = 0, items_after = 0):
    # Searches through the list of `items` until an item matching `predicate` is found.
    # Then return that item.
    # If no item matching predicate is found, return None.
    # Optionally, also return up to `items_before` items preceding the target, and
    # `items after` items after the target.
    #
    # Note:
    d = collections.deque (maxlen = items_before + 1 + items_after)
    iter1 = iterable.__iter__()
    iter2 = itertools.takewhile(lambda x: not(predicate(x)), iter1)    
    d.extend(iter2)

    # zero-length input, or no matching item
    if len(d) == 0 or not(predicate(d[-1])):
        return None

    # get context after match:
    try:
        for i in xrange(items_after):
            d.append(iter1.next())
    except StopIteration:
        pass

    if ( items_before == 0 and items_after == 0):
        return d[0]
    else:
        return list(d)

Usage should be like:

>>> get_item_with_context(lambda x: x == 3, [1,2,3,4,5,6],
                          items_before = 1, items_after = 1)
[2, 3, 4]

Problems with this:

  • Checking to make sure we actually found a match, using not(predicate(d[-1])), doesn’t work for some reason. It always returns false.
  • If there are less than items_after items in the list after the matching item is found, then the results are rubbish.
  • Other edge cases?

Can I please have some advice on how to make this work / make it more robust? Or, if I’m reinventing the wheel, feel free to tell me that too.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T03:55:48+00:00Added an answer on June 3, 2026 at 3:55 am

    This appears to handle edge cases correctly:

    from collections import deque
    
    def item_with_context(predicate, seq, before=0, after=0):
        q = deque(maxlen=before)
        it = iter(seq)
    
        for s in it:
            if predicate(s):
                return list(q) + [s] + [x for _,x in zip(range(after), it)]
            q.append(s)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm running into a common pattern in the code that I'm writing, where I
I find myself repeating a common pattern when trying to execute code across multiple
There are some common code patterns I find in other people's Java code that
This is becoming a common pattern in my code, for when I need to
A common pattern in C++ is to create a class that wraps a lock
I've noticed a common pattern in some code I'm writing so I decided to
I am trying to extract out the common code pattern here in an extract
I'm working with Spree, which uses Rails engines extensively. A common pattern I find
It’s a common pattern in my code to allocate an object, let it do
I've noticed that a common pattern I use is to assign SomeClass.__init__() arguments to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.