How to Get the First and Last Digit of a Number in Python

To get the last digit of a number in Python, use the modulo operator: number % 10. To get the first digit of a number in Python, convert it to a string and take the first character: int(str(number)[0]). Both work for any size of integer; use abs() first if the number can be negative. This tutorial shows each method with real output, a program that reads the number from the user, and the edge cases (negative numbers, zero, very large numbers and floats) where some popular methods fail.

All examples were run with Python 3.12.5 in the Windows Command Prompt; the screenshots show the real runs. The operators used here are described in the Python docs under numeric types and math.log10().

Quick answer

number = 58392

last_digit = number % 10              # remainder after dividing by 10
first_digit = int(str(number)[0])     # first character of the number as text

print("Number:", number)
print("First digit:", first_digit)
print("Last digit:", last_digit)

Output:

Number: 58392
First digit: 5
Last digit: 2
Command Prompt running a Python script that prints the first digit 5 and the last digit 2 of the number 58392
The quick answer running in the Command Prompt.

Get the last digit of a number

Dividing by 10 moves every digit one place to the right; the remainder is the digit that falls off, which is the last one:

n = 47815

print(n % 10)            # 1. modulo: the fastest and most common way
print(int(str(n)[-1]))   # 2. last character of the string
q, r = divmod(n, 10)     # 3. divmod gives the rest of the number too
print(r, "and the number without it:", q)

print(-4096 % 10, abs(-4096) % 10)   # negative numbers: use abs() first

Output:

5
5
5 and the number without it: 4781
4 6

n % 10 is the one to use. Watch out for negative numbers: Python’s modulo takes the sign of the divisor, so -4096 % 10 returns 4, not 6. Call abs() first, as the last line shows.

Get the first digit of a number

There is no single operator for the first digit, because its place value depends on how many digits the number has. Three common ways:

import math

n = 47815

# 1. string indexing
print(int(str(n)[0]))

# 2. while loop: keep dropping the last digit until one digit is left
m = n
while m >= 10:
    m //= 10
print(m)

# 3. logarithm: 10 ** (number of digits - 1) is the place value of the first digit
print(n // 10 ** int(math.log10(n)))

Output:

4
4
4
MethodCodeNotes
Stringint(str(n)[0])Shortest and exact for any integer; use abs(n) for negatives
While loopwhile n >= 10: n //= 10Pure arithmetic, common in exams; one step per digit
Logarithmn // 10 ** int(math.log10(n))Fails for 0 and negatives, and gives wrong answers for large numbers (see below)

Why the math.log10 method can give a wrong first digit

math.log10() works with floating-point numbers, which carry about 15-16 significant digits. For numbers made of many 9s the logarithm is rounded up to a whole number, so the place value is one too big and the result is 0:

import math

n = 999_999_999_999_999            # 15 nines
print("math.log10(n) =", math.log10(n))                      # rounded up to 15.0
print("log10 method  =", n // 10 ** int(math.log10(n)))      # wrong: 0
print("string method =", int(str(n)[0]))                     # right: 9

Output:

math.log10(n) = 15.0
log10 method  = 0
string method = 9
Command Prompt showing math.log10 of 999999999999999 rounded to 15.0 so the log10 first digit method returns 0 while the string method returns 9
The logarithm method breaks on 999,999,999,999,999; the string method does not.

Python integers have no size limit, and str() is exact for all of them, so prefer the string or loop method unless the numbers are known to be small.

A function that handles negative numbers and zero

def first_last_digits(n):
    """Return (first digit, last digit) of an integer, ignoring the sign."""
    s = str(abs(int(n)))
    return int(s[0]), int(s[-1])


for value in [58392, 7, 0, -4096, 12_000_000, 999_999_999_999_999_999]:
    first, last = first_last_digits(value)
    print(f"{value:>25,}  first={first}  last={last}  sum={first + last}")

Output:

                   58,392  first=5  last=2  sum=7
                        7  first=7  last=7  sum=14
                        0  first=0  last=0  sum=0
                   -4,096  first=4  last=6  sum=10
               12,000,000  first=1  last=0  sum=1
  999,999,999,999,999,999  first=9  last=9  sum=18
Command Prompt output of a Python function returning the first digit, last digit and their sum for positive, negative, zero and very large numbers
One function tested on positive, negative, zero and 18-digit numbers.

Program: display the first and last digit of a number entered by the user

A common exercise is to write a program to display the last digit of a number. This version reads the number with input(), accepts negative numbers and also prints the sum of the first and last digit:

number = int(input("Enter a number: "))

digits = str(abs(number))
print("First digit:", digits[0])
print("Last digit:", digits[-1])
print("Sum of first and last digit:", int(digits[0]) + int(digits[-1]))

Output (the user typed -58392):

Enter a number: -58392
First digit: 5
Last digit: 2
Sum of first and last digit: 7
Command Prompt running a Python program where the user types -58392 and the program displays first digit 5, last digit 2 and their sum 7
The program running with a number typed at the keyboard.

First two digits and last two digits

Slice more characters of the string, or use a bigger power of 10:

n = 8_245_137

print(int(str(n)[:2]))            # first two digits
print(int(str(n)[:3]))            # first three digits
print(n // 10 ** (len(str(n)) - 2))   # first two digits with arithmetic
print(n % 100)                    # last two digits

Output:

82
824
82
37

First and last digit of a float

For decimal numbers, decide which digit you mean: the last digit before the decimal point, or the last digit written. For values below 1, skip the leading zeros to get the first significant digit:

price = 482.75

print(int(str(price)[0]))            # first digit of a float: 4
print(int(price) % 10)               # last digit before the decimal point: 2
print(str(price).replace(".", "")[-1])   # last digit written: 5

small = 0.0073
first_significant = str(small).lstrip("0.")[0]   # skip leading zeros and the point
print(first_significant)                          # 7

Output:

4
2
5
7

Floats are stored in binary, so a number like 0.1 + 0.2 prints as 0.30000000000000004. If the digits matter (prices, measurements), keep the value as a string or a decimal.Decimal.

Practise with these related Python number programs:

Frequently asked questions

How do I get the last digit of a number in Python?

Use number % 10. For negative numbers use abs(number) % 10.

How do I get the first digit of a number in Python?

Use int(str(abs(number))[0]). Without strings, divide by 10 in a loop until the number is below 10.

How do I get the first digit of an int without converting to a string?

Use a loop: while n >= 10: n //= 10. The logarithm formula n // 10 ** int(math.log10(n)) also works for small positive numbers but gives 0 for large ones like 999,999,999,999,999.

How do I get the first two digits of a number in Python?

int(str(n)[:2]), or n // 10 ** (len(str(n)) - 2) for a positive integer with at least two digits.

How do I find the last digit of a negative number?

Take the absolute value first: abs(-4096) % 10 returns 6. Python’s -4096 % 10 returns 4, because modulo follows the sign of the divisor.

How do I write a program to display the first and last digit of a number?

Read it with int(input()), convert abs(number) to a string, and print the characters at index 0 and -1.