+ 3
How to fix this error so that num = [1,3,4] ?
lst = ['#',1,3,'*',4] num = [] for n in list: if type(n) == int: num = num.append(n) print(num)
6 Answers
+ 5
Your mistake in line3, 5:
Fixedđ:
lst = ['#',1,3,'*',4]
num = []
for n in lst:
if type(n) == int:
num.append(n)
print(num)
+ 4
My solution is a bit different.
#How to fix this error so that num = [1,3,4] ?
lst = ['#',1,3,'*',4]
nums = []
for i in lst:
i = str(i)
if i.isdigit():
nums.append(int(i))
print(nums)
+ 3
Anyways to get the answer you need to use try and except where while iterating you try to convert a value into an int if it fails then you except that and continue. since 1,2 and 4 would be able to get converted cause they already are int's it will work and give you the desired output.
here is the code:
lst = ['#',1,3,'*',4]
num=[]
for n in lst:
try:
num.append(int(n))
except:
continue
print(num)
+ 3
Alternative using list comprehension
num = [ e for e in lst if type(e) is int ]
+ 2
0
This isn't possible as you cant use type() to iterate something