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 another number (both as number or string) in the same index 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 there a way to check a specific list element if it is a number?
This could 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)])
But we can't check if a string can become an int in this specific case. Basically, using list comprehension, we filter the first list and we create a new list based on the second one, so we should implement a way to check if a string can become an int.
To do so, we need one more check (and we'll move to a foreach for better readability).
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])
In conclusion, isdigit()
is only available for strings, that's why you get the error. You loop through integers too, so it doesn't exist.
Note that this code is NOT flexible and it only covers the specific case. For example, if negative numbers are prompted or lists are of different lengths, it will break.
If we want to also cover the negative numbers case, a quick fix is to swap from x.isdigit()
to a try-except
, like so:
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):
try:
int(x)
output_list.append(list2[index])
except:
continue
If it can't be converted to int, then go to the next iteration.