Recommended Free Tools
For an integer, convert its absolute value to a string and take the first and last characters. Convert those characters to integers if you want numeric digits:
def first_and_last_digit(n: int) -> tuple[int, int]:
digits = str(abs(n))
return int(digits[0]), int(digits[-1])
print(first_and_last_digit(58392)) # (5, 2)
print(first_and_last_digit(-58392)) # (5, 2)
print(first_and_last_digit(0)) # (0, 0)
How the string method works
abs(n) removes a negative sign, and str(...) turns the integer into its decimal representation. Python strings are indexed from zero, so digits[0] is the first digit and digits[-1] is the last. The function returns integers because it wraps each character in int().
As an Amazon Associate I earn from qualifying purchases.
This assumes n is a valid Python integer. If you only need the digits as characters, return digits[0], digits[-1] without converting them.
Get only the last digit with modulo
If you need just the final decimal digit as an integer, use:
#1 Best Overall
last_digit = abs(n) % 10
Taking the absolute value makes the intended result clear for negative inputs. Python defines % as the remainder operator; its result has the sign of the divisor. Thus, -58392 % 10 is 8, not -2. See the Python 3.14.8 Built-in Types documentation.
Negative numbers and zero
The example treats a digit as part of the number’s magnitude: the minus sign is not a digit. That is why first_and_last_digit(-58392) returns (5, 2). Zero has one decimal digit, so the first and last digits are both 0.
Rank #2
Floats and text input need a defined format
Do not apply the integer version to a float without deciding what “digit” means. For example, converting a float to int truncates its fractional part; it does not extract digits from the formatted decimal representation. Choose whether you want digits from the integer part or characters from a particular formatted value. Python documents numeric conversion and related built-in behavior in its Built-in Types reference.
If the input arrives as text, validate it before indexing. Empty text and a sign-only string such as "-" contain no digits. Convert validated text to an integer first if the input is meant to represent an integer.
When arithmetic extraction is useful
Repeated modulo and floor division can process every digit without converting the number to text. For the simple task of getting only the first and last digits, string indexing is shorter and easier to read. Arithmetic extraction also needs an explicit policy for negative numbers because Python’s // is floor division. See the Python tutorial introduction for the documented operator behavior.
Quick Recap
Best Value
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




