+ 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)

28th Aug 2020, 8:48 AM
Rajan K
Rajan K - avatar
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)
28th Aug 2020, 8:54 AM
Vadivelan
+ 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)
28th Aug 2020, 10:04 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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)
28th Aug 2020, 9:14 AM
Kunsh-Tyagi
Kunsh-Tyagi - avatar
+ 3
Alternative using list comprehension num = [ e for e in lst if type(e) is int ]
28th Aug 2020, 9:29 AM
Ipang
+ 2
Kunsh-Tyagi Ipang has written a correct & elegant solution as has Vadi velan
28th Aug 2020, 10:08 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
This isn't possible as you cant use type() to iterate something
28th Aug 2020, 8:55 AM
Kunsh-Tyagi
Kunsh-Tyagi - avatar