How to return the sum of the last digits of the values in a list? i cant think of an efficient way. If it wasn't for being in a list i could do it, but im really lost. Can anyone advise me? im going to look for a way in the python library.
Thank you for any help

Dani AI

Generated

A simple and efficient way is to take each number’s last digit with the modulo operator and sum them. This runs in O(n) time, avoids any string conversion, and works for arbitrarily large integers. If you might encounter negative values, take the absolute value first so that -23 contributes 3. For non-integers, decide whether to reject them or explicitly convert; silently truncating floats can hide bugs.

def getSumofLastDigits(nums):
    """Return the sum of last digits for a list of integers."""
    return sum(abs(n) % 10 for n in nums)

# Optional: strict variant that enforces ints
def getSumofLastDigits_strict(nums):
    if not all(isinstance(n, int) for n in nums):
        raise TypeError("All elements must be integers.")
    return sum(abs(n) % 10 for n in nums)

Quick check:

getSumofLastDigits([10, 29, 305, 0])   # 0 + 9 + 5 + 0 = 14
getSumofLastDigits([8, 111, 42])       # 8 + 1 + 2 = 11
getSumofLastDigits([-7, -123])         # 7 + 3 = 10

Notes:

  • sum([]) returns 0, so an empty list is handled naturally.
  • Using a generator expression avoids creating an intermediate list.
  • divmod(n, 10)[1] also returns the last digit, but % 10 is clearer for this task.

Recommended Answers

All 5 Replies

If you think of something else than code under,give an example of list and task.

>>> l = [1,2,3,4]
>>> l[:2]
[1, 2]
>>> l[2:]
[3, 4]
>>> #Sum up last 2 digits
>>> sum(l[2:])
7

If you think of something else than code under,give an example of list and task.

>>> l = [1,2,3,4]
>>> l[:2]
[1, 2]
>>> l[2:]
[3, 4]
>>> #Sum up last 2 digits
>>> sum(l[2:])
7

sorry, i wasn't very clear of my intentions, forgive me. the objective is as follows;

Write a function getSumofLastDigits() that takes in a list of positive numbers and returns the sum of all the last digits in the list.

Examples

>>> getSumofLastDigits([2, 3, 4])
    9
    >>> getSumofLastDigits([1, 23, 456])
    10

You can use modulo operator to find the last digit.

Just to give you a hint with modulo operator as pyTony mention.

>>> 38 % 10
8
>>> 369 % 10
9
>>> 36 % 10
6
>>> 36999 % 10
9
>>>

So loop over element in list with modulo operator ,and use build in sum() to get result.

Thanks for the help everyone!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.