Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sort list of numbers by sum of their digits
Next article icon

Sum the Digits of a Given Number – Python

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of summing the digits of a given number in Python involves extracting each digit and computing their total . For example, given the number 12345, the sum of its digits is 1 + 2 + 3 + 4 + 5 = 15. 

Using modulo (%)

This method efficiently extracts each digit using the modulus (%) and integer division (//) operations, avoiding unnecessary string conversions. It is the fastest and most memory-efficient approach, making it ideal for performance-focused applications.

Python
n = 12345 sum = 0  while n > 0:     sum += n % 10  # extract last digit     n //= 10       # remove last digit  print(sum) 

Output
15 

Explanation: This code iterates through the digits of n, extracting each last digit using % 10, adding it to sum and removing it with // 10 until n becomes 0.

Table of Content

  • Using recursion
  • Using map()
  • Using reduce

Using recursion

This method uses recursion to break the problem into smaller subproblems. It follows the same mathematical approach but introduces function call overhead, making it slightly less efficient than the iterative method. It is useful when a recursive solution is preferred.

Python
# recursive function  def fun(n):     if n == 0:         return 0  # base case     return (n % 10) + fun(n // 10)  n = 12345 print(fun(n)) 

Output
15 

Explanation: fun(n) recursively sums the digits of n. If n is 0, it returns 0. Otherwise, it adds the last digit (% 10) to the sum of a recursive call on the remaining digits (// 10), repeating until n becomes 0.

Using map()

map() apply the int() conversion directly, reducing memory usage. It provides a more functional programming style but still involves string conversion and making it less efficient than mathematical methods.

Python
n = 12345  sum = sum(map(int, str(n))) print(sum) 

Output
15 

Explanation: This code converts n to a string, maps each digit to an integer and sums them using sum().

Using reduce

functools.reduce() applies a cumulative operation to the digits. Although some may prefer this approach, it adds unnecessary function call overhead, making it the least efficient method for this problem.

Python
from functools import reduce  n = 12345 sum = reduce(lambda x, y: x + int(y), str(n), 0) print(sum) 

Output
15 

Explanation: This converts n to a string, then applies a lambda function that iteratively adds each digit (converted to an integer) to an accumulator, starting from 0.



Next Article
Python - Sort list of numbers by sum of their digits

S

SHUBHAMSINGH10
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Sum of number digits in List in Python
    Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Python’s built-in functions like sum(), map(), and list comprehensions. For exa
    2 min read
  • Python - Sort list of numbers by sum of their digits
    Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case. Using sorted() with a Lambda Functionsorted() function
    2 min read
  • Python3 Program to Rotate digits of a given number by K
    INTRODUCTION:One important point to consider when working with the algorithm to rotate the digits of a given number by k positions is the time complexity. If we were to implement this algorithm using the approach shown in the previous example, the time complexity would be O(n), where n is the number
    4 min read
  • Python Program to Get Sum of N Armstrong Number
    Given a number N, determine the sum of the first N Armstrong numbers using Python. Example: Input : 11Output : 568First 11 Armstrong numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, lies to, 370Their summation is 578Method 1: Using Iterative methodsCreate a while loop that breaks when the desired number of Ar
    3 min read
  • Number System in Python
    The arithmetic value that is used for representing the quantity and used in making calculations is defined as NUMBERS. The writing system for denoting numbers logically using digits or symbols is defined as a Number system. Number System is a system that defines numbers in different ways to represen
    6 min read
  • Python - Average of digit greater than K
    Given elements list, extract elements whose average of digit is greater than K. Input : test_list = [633, 719, 8382, 119, 327], K = 5 Output : [719, 8382] Explanation : (7 + 1 + 9) / 3 = 5.6 and (8 + 3 + 8 + 2) / 4 = 5.2 , both of which are greater than 5, hence returned. Input : test_list = [633, 7
    5 min read
  • Insert a number in string - Python
    We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
    2 min read
  • Python program to sort digits of a number in ascending order
    Given an integer N, the task is to sort the digits in ascending order. Print the new number obtained after excluding leading zeroes. Examples: Input: N = 193202042Output: 1222349Explanation: Sorting all digits of the given number generates 001222349.Final number obtained after removal of leading 0s
    2 min read
  • Python - Get summation of numbers in string list
    Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute force method to perform this
    3 min read
  • Python Program to Find Sum of First and Last Digit
    Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digits of the given number N. Examples: Input: N = 1247 Output: 8 Explanation: First digit is 1 and Last digit is 7. So, addition of these two (1 + 7) is equal to 8.Input: N = 73
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences