Python: How to extract the last 3 digits of each object in my list full of integers?

Viewed 1274

I have a list of integers. Each integer has 6 digits. For example:

ids = [335381, 779097, 147786, 951524]

I want to make a new list that only contains the last 3 digits for each of these ids, the output should look like this:

new_ids = [381, 097, 786, 524]

Any ideas? Thanks!

3 Answers

Very efficient answers have been given. These are just two other methods that can be used - user case depending: slicing and regex.

Simple Slicing:

[int(str(i)[-3:]) for i in ids]

>>> [381, 97, 786, 524]

Regex:

import re

exp = re.compile('(\d{3})$')
[int(exp.findall(str(i))[0]) for i in ids]

>>> [381, 97, 786, 524]

Solution

You may do modulo 1000:

ids = [335381, 779097, 147786, 951524]
ids = [i%1000 for i in ids]            # [381, 97, 786, 524]

Note

Note that 097 as digit is not a valid representation, 97 is right, to see it as 3 digits with a 0-leading you need a string representation


Bench

As there is multiple answer, I'm adding a little timeit scores

import timeit

r = timeit.timeit("[i%1000 for i in ids]", setup="ids = [335381, 779097, 147786, 951524]")
print(str(round(r, 2)) + 'µs, per iteration')

r = timeit.timeit("[int(str(i)[-3:]) for i in ids]", setup="ids = [335381, 779097, 147786, 951524]")
print(str(round(r, 2)) + 'µs, per iteration')

r = timeit.timeit("[int(exp.findall(str(i))[0]) for i in ids]",
                  setup=r"ids = [335381, 779097, 147786, 951524];import re;exp = re.compile('(\d{3})$')")
print(str(round(r, 2)) + 'µs, per iteration') 

Results

0.75µs, per iteration     
5.5µs, per iteration     # modulo is about  6 times faster
12.86µs, per iteration   # modulo is about 15 times faster

The last three digits are the remainder after dividing by 1000.

new_ids = [x % 1000 for x in ids]

If you specifically want 097, you'll have to use strings.

# Convert the result to a zero-padded string
new_ids = [f'{x%1000:03}' for x in ids]  # Pad the remainder with 0s

or

# Convert to a string of at least 3 digits, then take the last 3
new_ids = [f'{x:03}'[-3:] for x in ids]
Related