Home > Software engineering >  How Can I find only those numbers in a numerical list that end with the digit 3 in python?
How Can I find only those numbers in a numerical list that end with the digit 3 in python?

Time:02-20

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)

CodePudding user response:

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']

CodePudding user response:

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'])

CodePudding user response:

If you don't need one-liner solution:

result = []
for i in output_list:
    if i[-1] == '3':
        result.append(int(i))

print(result)
  • Related