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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T16:51:22+00:00 2026-06-09T16:51:22+00:00

I was writing some Python code that involved something like this values = {}

  • 0

I was writing some Python code that involved something like this

values = {}
for element in iterable:
    values.setdefault(element.name, []).append(element)

Because I could have sorted the input previously, I also implemented it like this

values = {}

cur_name = None
cur_list = None

for element in iterable:
    if element.name != cur_name:
        values[cur_name] = cur_list
        cur_name = element.name
        cur_list = []
    cur_list.append(element)
if cur_list:
    values[cur_name] = cur_list
del values[None]

Here the input is already sorted by element.name.

The second approach was much faster than the first approach, and it also used less memory.

What’s the reason for this?

Or have I made some sort of mistake in the second approach?

  • 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-09T16:51:22+00:00Added an answer on June 9, 2026 at 4:51 pm

    Your original code every time round the loop will create a list that mostly then just gets thrown away. It also makes multiple dictionary lookups (looking up the method setdefault is a dictionary lookup and then the method itself does a dictionary lookup to see whether the object was set and if it isn’t does another to store the value). .name and .append() are also dictionary lookups but they are still present in the revised code.

    for element in iterable:
        values.setdefault(element.name, []).append(element)
    

    The revised code only looks up the dictionary when the name changes, so it it removes two dictionary lookups and a method call from every loop. That’s why it’s faster.

    As for the memory use, when the list grows it may sometimes have to copy the data but can avoid that if the memory block can just be expanded. My guess would be that creating all of those unused temporary lists may be fragmenting the memory more and forcing more copies. In other words Python isn’t actually using more memory, but it may have more allocated but unused memory.

    When you feel a need for setdefault consider using collections.defaultdict instead. That avoids creating the list except when it’s needed:

    from collections import defaultdict
    values = defaultdict(list)
    for element in iterable:
        values[element.name].append(element)
    

    That will probably still be slower than your second code because it doesn’t take advantage of your knowledge that names are all grouped, but for the general case it is better than setdefault.

    Another way would be to use itertools.groupby. Something like this:

    from itertools import groupby
    from operator import attrgetter
    values = { name: list(elements) for name,elements in
        groupby(elements, attrgetter('name')) }
    

    That takes advantage of the ordering and simplifies everything down to a single dictionary comprehension.

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

Sidebar

Related Questions

I am writing some code in Python something like this: import sys try: for
I'm writing some python code to interact with a C DLL that uses structures
I'm writing some serialization/deserialization code in Python that will read/write an inheritance hierarchy from
I'm writing some code (Python, but really isn't important) that analyzes strings inside PE
Im running into this error that I can't work out Im writing some code
I'm writing some python code that's supposed to parse a CSV file. Calculate the
I am writing some Python code that uses a library to communicate with an
I'm writing some code to determine the name that an object is assigned to.
What are the current rules for writing python code that will pass cleanly through
I'm writing some speech recognition code in python and I want it to be

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.