Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a specific list element is a number?

I have 2 lists, one that contains both numbers and strings and one only numbers.

list1 = [1,2,'A','B',3,'4']
list2 = [1,2,3,4,5,6]

My goal is to print from list2 only the numbers that have a corresponding number (both as number or string) in list1.
Expected output:

[1,2,5,6]

I have tried the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lenght1 = len(list1)

for i in range(lenght1):
    if (list1[i].isdigit()): 
        print(list2[i])

But I receive the following error:

AttributeError: 'int' object has no attribute 'isdigit'

Same error with .isnumber().

Is the a way to check a specific list element if it is a number?

>Solution :

This can be solved in a one-liner solution, like so:

list1 = [1,2,'A','B',3,'4']
list2 = [1,2,3,4,5,6]

print([list2[index] for index, x in enumerate(list1) if isinstance(x, int)])

Basically, through list comprehension, we filter the first list and we create a new list based on the second one. But we can’t check if a string can become an int.

isdigit() is only available for strings. You get the error because you loop through integers, so it doesn’t exist. To do so, we need one more check and move to a foreach.

list1 = [1,2,'A','B',3,'4']
list2 = [1,2,3,4,5,6]
output_list = []
for index, x in enumerate(list1):
    if isinstance(x, int):
        output_list.append(list2[index])
    if isinstance(x, str):
        if x.isdigit():
            output_list.append(list2[index])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading