How to Get the Last Digit of an Integer in Python?

Getting the last digit of a Python integer

In Python, you can get the last digit of an integer in the following ways:

Using Modulo Operator

You can use the modulo operator (%) to get the last digit of an integer in the following way:

  1. Convert number to absolute form;
  2. Get the last digit by calculating number % 10;
  3. Add negative sign to the last digit if integer was negative.

The modulo operator in Python won't return the correct last digit for negative numbers because it performs floored division, and not truncated division. To get the correct result, you must convert the number to absolute form first (using abs()), and then add the sign back.

For example:

def last_digit(num):
    last_digit_unsigned = abs(num) % 10
    return -last_digit_unsigned if (num < 0) else last_digit_unsigned

print(last_digit(0)) # 0
print(last_digit(1234)) # 4
print(last_digit(-1234)) # -4

As an alternative, you may use the following mathematical formula for calculating remainder correctly:

def last_digit(num):
    return num - (10 * int(num / 10))

print(last_digit(0)) # 0
print(last_digit(1234)) # 4
print(last_digit(-1234)) # -4

This performs truncated division (i.e. using the int() method, the fraction part is removed/truncated from the result of the division).

This works in the following way:

# num = 1234

# last_digit = 1234 - (10 * int(1234 / 10))
# last_digit = 1234 - (10 * int(123.4))
# last_digit = 1234 - (10 * 123)
# last_digit = 1234 - 1230
# last_digit = 4

Converting to String and Retrieving Last Character

You could do the following:

  1. Convert the integer to a string;
  2. Get the last character of the string;
  3. Convert the string back to integer;
  4. Add negative sign to the last digit if integer was negative.
def last_digit(num):
    num_str = str(num)
    last_digit_unsigned = int(num_str[-1])
    return -last_digit_unsigned if (num < 0) else last_digit_unsigned

print(last_digit(0)) # 0
print(last_digit(1234)) # 4
print(last_digit(-1234)) # -4

When the integer is converted to a string, the sign is considered a character in the string and has no special meaning, which is why it is not added to the last digit. For this reason, the sign is added back once the last character is converted back to an integer.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.