'How Can I find only those numbers in a numerical list that end with the digit 3 in python?

The question is as follow:

Write a code to find only those numbers in the list that end with the digit 3. Store the results in an empty list called “output_list”. Note: for this one you have to convert the integers to strings and use indexing to find the last digit.

We have the list:

x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]

First I try to convert the integers into a strings data types with a for loop.

output_list = []

for i in x:

    output_list.append(str(i))

print(output_list)

and the output is:

['12', '43', '4', '1', '6', '343', '10', '34', '12', '93', '783', '330', '896', '1', '55']

Then, finding the numbers in the list that end with the digit 3. I'm using this for loop to find the numbers that end with the digit 3, but it does not work.

for i in output_list:

    if(output_list[len(i) -1]=='3'):

        print(output_list)


Solution 1:[1]

Simple pythonic one liner:

x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]
output_list = [str(i) for i in x if str(i)[-1]=="3"]
print(output_list) # ['43', '343', '93', '783']

Solution 2:[2]

I have no idea why you're being asked to convert the integers to strings in order to achieve this. That's woefully inefficient when all you need is:

x = [12,43,4,1,6,343,10, 34, 12, 93, 783, 330, 896, 1, 55]

print([v for v in x if v % 10 == 3])

Output:

[43, 343, 93, 783]

However, for the sake of completeness, you could do this a fulfil the brief:

print([v for v in x if str(v)[-1] == '3'])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhinav Mathur
Solution 2 Albert Winestein