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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T04:40:49+00:00 2026-05-16T04:40:49+00:00

I have a list of integers which I need to parse into a string

  • 0

I have a list of integers which I need to parse into a string of ranges.

For example:

 [0, 1, 2, 3] -> "0-3"
 [0, 1, 2, 4, 8] -> "0-2,4,8"

And so on.

I’m still learning more pythonic ways of handling lists, and this one is a bit difficult for me. My latest thought was to create a list of lists which keeps track of paired numbers:

[ [0, 3], [4, 4], [5, 9], [20, 20] ]

I could then iterate across this structure, printing each sub-list as either a range, or a single value.

I don’t like doing this in two iterations, but I can’t seem to keep track of each number within each iteration. My thought would be to do something like this:

Here’s my most recent attempt. It works, but I’m not fully satisfied; I keep thinking there’s a more elegant solution which completely escapes me. The string-handling iteration isn’t the nicest, I know — it’s pretty early in the morning for me 🙂

def createRangeString(zones):
        rangeIdx = 0
        ranges   = [[zones[0], zones[0]]]
        for zone in list(zones):
            if ranges[rangeIdx][1] in (zone, zone-1):
                ranges[rangeIdx][1] = zone
            else:
                ranges.append([zone, zone])
                rangeIdx += 1

        rangeStr = ""
        for range in ranges:
            if range[0] != range[1]:
                rangeStr = "%s,%d-%d" % (rangeStr, range[0], range[1])
            else:
                rangeStr = "%s,%d" % (rangeStr, range[0])

        return rangeStr[1:]

Is there a straightforward way I can merge this into a single iteration? What else could I do to make it more Pythonic?

  • 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-16T04:40:50+00:00Added an answer on May 16, 2026 at 4:40 am
    >>> from itertools import count, groupby
    >>> L=[1, 2, 3, 4, 6, 7, 8, 9, 12, 13, 19, 20, 22, 23, 40, 44]
    >>> G=(list(x) for _,x in groupby(L, lambda x,c=count(): next(c)-x))
    >>> print ",".join("-".join(map(str,(g[0],g[-1])[:len(g)])) for g in G)
    1-4,6-9,12-13,19-20,22-23,40,44
    

    The idea here is to pair each element with count(). Then the difference between the value and count() is constant for consecutive values. groupby() does the rest of the work

    As Jeff suggests, an alternative to count() is to use enumerate(). This adds some extra cruft that needs to be stripped out in the print statement

    G=(list(x) for _,x in groupby(enumerate(L), lambda (i,x):i-x))
    print ",".join("-".join(map(str,(g[0][1],g[-1][1])[:len(g)])) for g in G)
    

    Update: for the sample list given here, the version with enumerate runs about 5% slower than the version using count() on my computer

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

Sidebar

Related Questions

Say you need to have a list/array of integers which you need iterate frequently,
I have a list of integers, List<Integer> and I'd like to convert all the
I have a list of integers in C#. I wish to remove duplicates. In
Does anyone have a good algorithm for taking an ordered list of integers, i.e.:
If I have List<String> text how can I create a sub-list of all continious
I have a List of Foo. Foo has a string property named Bar. I'd
I have a list, each item of which has several things in it, including
I have a list of more than 15 thousand latitude and longitude coordinates. Given
In a report model I have some entities which have attributes which are integers
I have a pretty big SQL statement which returns a list of id's. I

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.