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 843205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T06:05:16+00:00 2026-05-15T06:05:16+00:00

In a Python program I’m writing I’ve compared using a for loop and increment

  • 0

In a Python program I’m writing I’ve compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach?

Here is a greatly simplified and shortened data structure:

list = [
  {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'},
  {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'},
  {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'},
  {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'},
  {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'}
]

Here is the for loop version:

#!/usr/bin/env python
# Python 2.6
# count the entries where key1 is True
# keep a separate count for the subset that also have key2 True

key1 = key2 = 0
for dictionary in list:
    if dictionary["key1"]:
        key1 += 1
        if dictionary["key2"]:
            key2 += 1
print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)

Output for the data above:

Counts: key1: 3, subset key2: 2

Here is the other, perhaps more Pythonic, version:

#!/usr/bin/env python
# Python 2.6
# count the entries where key1 is True
# keep a separate count for the subset that also have key2 True
from operator import itemgetter
KEY1 = 0
KEY2 = 1
getentries = itemgetter("key1", "key2")
entries = map(getentries, list)
key1 = len([x for x in entries if x[KEY1]])
key2 = len([x for x in entries if x[KEY1] and x[KEY2]])
print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)

Output for the data above (same as before):

Counts: key1: 3, subset key2: 2

I’m a tiny bit surprised these take the same amount of time. I wonder if there’s something faster. I’m sure I’m overlooking something simple.

One alternative I’ve considered is loading the data into a database and doing SQL queries, but the data doesn’t need to persist and I’d have to profile the overhead of the data transfer, etc., and a database may not always be available.

I have no control over the original form of the data.

The code above is not going for style points.

  • 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-05-15T06:05:17+00:00Added an answer on May 15, 2026 at 6:05 am

    I think you’re measuring incorrectly by swamping the code to be measured in a lot of overhead (running at top module level instead of in a function, doing output). Putting the two snippets into functions named forloop and withmap, and adding a * 100 to the list’s definition (after the closing ]) to make the measurement a little substantial, I see, on my slow laptop:

    $ py26 -mtimeit -s'import co' 'co.forloop()'
    10000 loops, best of 3: 202 usec per loop
    $ py26 -mtimeit -s'import co' 'co.withmap()'
    10 loops, best of 3: 601 usec per loop
    

    i.e., the allegedly “more pythonic” approach with map is three times slower than the plain for approach — which tells you that it’s not really “more pythonic”;-).

    The mark of good Python is simplicity, which, to me, recommends what I hubris-ly named…:

    def thebest():
      entries = [d['key2'] for d in list if d['key1']]
      return len(entries), sum(entries)
    

    which, on measurement, saves between 10% and 20% time over the forloop approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 513k
  • Answers 513k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer OK, now I know what you want. There is currently… May 16, 2026 at 5:58 pm
  • Editorial Team
    Editorial Team added an answer You shouldn't need to parse your JSON. Set the dataType… May 16, 2026 at 5:58 pm
  • Editorial Team
    Editorial Team added an answer You shouldn't do that. There is not a thing called… May 16, 2026 at 5:58 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

My python program (Python 2.6) works fine when I run it using the Python
A Python program I'm writing is to read a set number of lines from
The Python program I'm writing needs to start a local PHP script outside of
Is there a way to program using pure python in Xcode? I want something
my Python program can be launched with a range of different options (or subcommands)
A python program needs to draw histograms. It's ok to use 3rd party library
A python program that I'm debugging has the following code (including print statements for
My python program generates a collection of binary files. I create pgm (portable bitmap
My python program has two calls to raw_input() The first raw_input() is to take
Consider this Python program which uses PyGtk and Hippo Canvas to display a clickable

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.