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

  • Home
  • SEARCH
  • 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 8679901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T21:06:18+00:00 2026-06-12T21:06:18+00:00

I was recently working on this question . Essentially, my answer involved a call

  • 0

I was recently working on this question. Essentially, my answer involved a call to sorted with a lambda as the key:

sorted(range(len(L)), key=lambda i : L[i])

Given that performance was at the core of the question, and that lambdas are inherently slow, I could have optimized a bit by defining a function and using it in place of the lambda.

Still, I feel that that I’d be reinventing the wheel. There has to be a built-in function somewhere or in some importable module that provides the functionality of __getitem__ (which, the only reason I don’t want to use, is that it’s not really pythonic to use mangled methods).

I know about operator.getitem which let’s me predefine an index i and get the element at i in any input sequence. But is there a function (say foo) that works as follows:

In [14]: g = operator.itemgetter(1)

In [15]: d = {'a':1, 'b':2, 'c':3, 'd':4}

In [16]: for i in d.iteritems():
   ....:     print g(i),
   ....:     
1 3 2 4

In [17]: L = list('abcd')

In [18]: g = foo(L)

In [19]: for i in range(4):
   ....:     print g(i),
   ....:     
'a' 'b' 'c' 'd'

Sorry if this is a duplicate question, but the search words that I could think of did not yield results.

  • 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-12T21:06:19+00:00Added an answer on June 12, 2026 at 9:06 pm

    If I’ve understood what you want correctly, the following would do that:

    import functools
    import operator
    
    L = list('abcd')
    
    def foo(indexable):
        return functools.partial(operator.__getitem__, indexable)
    
    g = foo(L)
    
    for i in xrange(len(L)):
        print g(i),
    

    Update:

    I’ve experimented further and was surprised to discover a slightly faster solution, which is this nothing other than simply this:

    def foo2(indexable):
        return indexable.__getitem__
    

    Which, when run using a little testbed I threw together, produced the following results:

    fastest to slowest *_test() function timings:
     10,000 elements, 1,000 timeit calls, best of 3
    
      foo2_test() : 1.46 (0.00 times slower)
    lambda_test() : 4.15 (1.84 times slower)
       foo_test() : 4.28 (1.93 times slower)
    

    Each test function used just access each element of a list in a tight loop using a different technique.

    Curious about how this applied to your sorting answer to the linked question, I obtained these differing results using it for sorting a list rather than just accessing each of the list’s elements once:

    fastest to slowest *_test() function timings:
     10,000 elements, 1,000 timeit calls, best of 3
    
      foo2_test() : 13.03 (0.00 times slower)
       foo_test() : 14.70 (0.13 times slower)
    lambda_test() : 16.25 (0.25 times slower)
    

    While foo2() was the fastest In both cases, in the sorting version it was only so by a very small amount.

    Here’s a listing of the full testbed used to get the first set of results for simple access:

    import functools
    import operator
    
    import timeit
    import types
    
    N = 1000
    R = 3
    SZ = 10000
    SUFFIX = '_test'
    SUFFIX_LEN = len(SUFFIX)
    
    def setup():
        import random
        global a_list
        a_list = [random.randrange(100) for _ in xrange(SZ)]
    
    def lambda_test():
        global a_list
        f = lambda i: a_list[i]
        for i in xrange(len(a_list)): f(i)
    
    def foo(indexable):
        return functools.partial(operator.__getitem__, indexable)
    
    def foo_test():
        global a_list
        g = foo(a_list)
        for i in xrange(len(a_list)): g(i)
    
    def foo2(indexable):
        return indexable.__getitem__
    
    def foo2_test():
        global a_list
        g = foo2(a_list)
        for i in xrange(len(a_list)): g(i)
    
    # find all the functions named *SUFFIX in the global namespace
    funcs = tuple(value for id,value in globals().items()
                if id.endswith(SUFFIX) and type(value) is types.FunctionType)
    
    # run the timing tests and collect results
    timings = [(f.func_name[:-SUFFIX_LEN],
                min(timeit.repeat(f, setup=setup, repeat=R, number=N))
               ) for f in funcs]
    timings.sort(key=lambda x: x[1])  # sort by speed (ironic use of lambda?)
    fastest = timings[0][1]  # time fastest one took to run
    longest = max(len(t[0]) for t in timings) # len of longest func name (w/o suffix)
    
    print 'fastest to slowest *_test() function timings:\n' \
          ' {:,d} elements, {:,d} timeit calls, best of {:d}\n'.format(SZ, N, R)
    
    def times_slower(speed, fastest):
        return speed/fastest - 1.0
    
    for i in timings:
        print "{0:>{width}}{suffix}() : {1:.2f} ({2:.2f} times slower)".format(
                    i[0], i[1], times_slower(i[1], fastest), width=longest, suffix=SUFFIX)
    

    And here’s the portion that was different when testing sort usage:

    def setup():
        import random
        global a_list
        a_list = [random.randrange(100) for _ in xrange(SZ)]
    
    def lambda_test():
        global a_list
        sorted(range(len(a_list)), key=lambda i:a_list[i])
    
    def foo(indexable):
        return functools.partial(operator.__getitem__, indexable)
    
    def foo_test():
        global a_list
        sorted(range(len(a_list)), key=foo(a_list))
    
    def foo2(indexable):
        return indexable.__getitem__
    
    def foo2_test():
        global a_list
        sorted(range(len(a_list)), key=foo2(a_list))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I recently started working with a client that had an index.html file with this
I've recently been working with code that looks like this: using namespace std; class
I've been working on topcoder recently and I stumbled upon this question which I
I recently asked this question regarding pulling beans out of an applicationContext. The answer
I was given this question at a job interview recently and couldn't figure out
This question and its answer, which was recently tagged as an Epic Answer, has
This is a very elementary I realize, I have recently started working with asp.net
I am working with zend just recently. I discovered this ViewScript decorator for form
recently, while working on a db2 -> oracle migration project, we came across this
I've recently updated to Selenium 2.24.1 to get Firefox 13 working. With this update

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.