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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:55:41+00:00 2026-06-18T00:55:41+00:00

What is the best practice for iterating over an integer in Python? I find

  • 0

What is the best practice for iterating over an integer in Python? I find that I need to do so often, typically with verbose results. For example, here are two functions I wrote for Project Euler problems:

def is_permutation_of(n, m):
    """ Return True if n is a permutation of m, else False
    """
    if len(str(n)) != len(str(m)):
        return False
    for d in str(n):
        if d not in str(m):
            return False
    return True

And another:

def has_even_digit(n):
    """ Return True if n has an even digit, else False
    """
    evens = ['0', '2', '4', '6', '8']
    for e in evens:
        if e in str(n):
            return True
    return False

In addition to the verbosity, 1) there must be a computational expense associated with each type conversion and 2) it just feels completely inelegant. Is there another way of dealing with this issue? Am I going about these functions in entirely the wrong way, i.e. should I not have to ever iterate over an integer?

Thanks for any help.

  • 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-18T00:55:43+00:00Added an answer on June 18, 2026 at 12:55 am

    I prefer my variant instead of your is_permutation_of:

    def is_perm(a,b): return sorted(str(a)) == sorted(str(b))
    

    And I think this is better for has_even_digit

    def has_even_digit(n):
        evens=set(['0', '2', '4', '6', '8'])
        return any(c in evens for c in str(n))
    

    Or, even use a tuple rather than a set:

    def has_even_digit(n):
        return any(c in ('0', '2', '4', '6', '8') for c in str(n))
    

    Edit

    From the comment thread, I thing you are looking for something like this:

    # pseudo code -- don't use -- not syntactically correct
    for d in 123456:      # integer
       # do something with each digit...
    

    This does not work because integers do not support iteration in Python. Additionally, there is no real need have something like an integer iteration since it is so idiomatic and easy to do it with strings.

    Here is a Python framework to do it with strings but produce single integer digit:

    for d in [int(c) for c in str(123456)]:
        # d is a left (most significant) to right integer digit - do what you want with it...
    

    If you want the same number right to left:

    for d in [int(c) for c in str(123456)[::-1]]:
        # Now right (least significant digit) to left (most significant digit)
    

    Compare those two simple cases with doing it with actual math with the integer or long:

    def int_iter(n,reverse=False):
        rtr=[]
        if not isinstance(n, (int,long)):
            raise ValueError('n must be int or long')
    
        while n:
            rtr.append(n%10)
            n/=10
    
        if reverse:
            return rtr[::-1]    
        else:
            return rtr  
    

    It is really a lot easier to use strings and probably faster. If you need blazing speed, do it in C.

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

Sidebar

Related Questions

I'm looking for some best practice advice here. I have a library that I'd
The best practice seems to be to use assert for a condition that should
What is the best practice way of manually iterating (i.e., one at a time
I have an ArrayList that I want to iterate over. While iterating over it
Best practice is to use unique ivs, but what is unique? Is it unique
Short best practice question: If an object A is injected into another object B,
The 'best practice' (as I see it) to atomically create a new file, is
What would be the best practice to keep the user logged in if he
Is there a best practice for making an entity immutable? Users create exercises in
What is the best practice for generating valid XML with PHP from user submitted

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.