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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T01:39:47+00:00 2026-05-15T01:39:47+00:00

There are many ways to write a Python program that computes a histogram. By

  • 0

There are many ways to write a Python program that computes a histogram.

By histogram, I mean a function that counts the occurrence of objects in an iterable and outputs the counts in a dictionary. For example:

>>> L = 'abracadabra'
>>> histogram(L)
{'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2}

One way to write this function is:

def histogram(L):
    d = {}
    for x in L:
        if x in d:
            d[x] += 1
        else:
            d[x] = 1
    return d

Are there more concise ways of writing this function?

If we had dictionary comprehensions in Python, we could write:

>>> { x: L.count(x) for x in set(L) }

but since Python 2.6 doesn’t have them, we have to write:

>>> dict([(x, L.count(x)) for x in set(L)])

Although this approach may be readable, it is not efficient: L is walked-through multiple times. Furthermore, this won’t work for single-life generators; the function should work equally well for iterator generators such as:

def gen(L):
    for x in L:
        yield x

We might try to use the reduce function (R.I.P.):

>>> reduce(lambda d,x: dict(d, x=d.get(x,0)+1), L, {}) # wrong!

Oops, this does not work: the key name is 'x', not x. 🙁

I ended with:

>>> reduce(lambda d,x: dict(d.items() + [(x, d.get(x, 0)+1)]), L, {})

(In Python 3, we would have to write list(d.items()) instead of d.items(), but it’s hypothethical, since there is no reduce there.)

Please beat me with a better, more readable one-liner! 😉

  • 1 1 Answer
  • 1 View
  • 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-15T01:39:48+00:00Added an answer on May 15, 2026 at 1:39 am

    Python 3.x does have reduce, you just have to do a from functools import reduce. It also has “dict comprehensions”, which have exactly the syntax in your example.

    Python 2.7 and 3.x also have a Counter class which does exactly what you want:

    from collections import Counter
    cnt = Counter("abracadabra")
    

    In Python 2.6 or earlier, I’d personally use a defaultdict and do it in 2 lines:

    d = defaultdict(int)
    for x in xs: d[x] += 1
    

    That’s clean, efficient, Pythonic, and much easier for most people to understand than anything involving reduce.

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

Sidebar

Ask A Question

Stats

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

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

    • 7 Answers
  • Editorial Team

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

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The general attitude for phone-home code in local applications seems… May 16, 2026 at 10:42 pm
  • Editorial Team
    Editorial Team added an answer You can create a class variable (array) and in constructor… May 16, 2026 at 10:42 pm
  • Editorial Team
    Editorial Team added an answer Considering the distributed nature of GAE, I don't think you… May 16, 2026 at 10:42 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

There're many ways to write an HTTP-status header: HTTP/1.1 404 Not Found Status: 404
There are now so many ways to write windows apps, win32, MFC, ATL, .NET,
There are many ways we can deal with CSS browser compatibility issue. Such as
Im finding jQuery to difficult to learn as there seems to be many ways
I know there are many tutorials out there for getting started in C. However
Hannuka, Chanukah, Hanukkah...Due to transliteration from another language and character set, there are many
I have found some similar questions like this one, however there are so many
I have attempted this is many ways but failed consistently, hopefully you can help
After five years of professional Java (and to a lesser extent, Python) programming and
Let's assume that I have a complex hash reference $hash_ref , and I would

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.