Home > Mobile >  How to get the last digit from every list value?
How to get the last digit from every list value?

Time:07-03

Hi I want to take the last number of values from a list.

Example:

my_list = [1234, 2345, 3456, 4567]

And I want a result like this.

my_list_result = [4, 5, 6, 7]

Thanks so much!

CodePudding user response:

The last digit of any integer can be obtained using mod 10. So you can do this:

my_list_result = [x % 10 for x in my_list]

CodePudding user response:

you can use list comprehension like this

my_list = [i for i in my_list]

CodePudding user response:

you can convert the each item as a string and get the last element. You can convert it back to int after as

[str(num)[-1] for num in my_list]

with convert back to int

[int(str(num)[-1]) for num in my_list]

CodePudding user response:

Easy:

[int(str(n)[-1]) for n in my_list]

For each number in the list, turn it into a string, get the last character, and then turn that character into an int again.

  • Related