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