Most efficient way to look for the last digit of a number?
Question: I recently had a question in a Python exam where we were asked to check for
numbers to be ending in 8 and I came across two ways and I was wondering which
one was the most efficient or if there was an even better way to do so.

(If n is the desired number) So, method 1:

    
    
    if n % 10 == 8:
        //do stuff here
    

Method 2:

    
    
    if str(n)[-1] == 8:
        //do stuff here
    


Answer: You could easily test this yourself with Python's built-in
[`timeit.timeit`](https://docs.python.org/3/library/timeit.html#timeit.timeit)
function:

    
    
    >>> from timeit import timeit
    >>> n = 12345678
    >>> timeit("n % 10 == 8", "from __main__ import n")
    0.45508130223254284
    >>> timeit("str(n)[-1] == '8'", "from __main__ import n")
    1.689859186013905
    >>>
    

As you can see from the results above, the first solution is very efficient
and outperforms the second by almost four times.

