+ 1

Don't understand why 1 not print

#Not print element from list lst = ["#",1,2,"4","a",3] num = [] for n in lst: if type(n) == int: try: num = num.append(n) except: print(n) #number 1 not print. Output only 2 and 3 from list "lst". I do not understand why

26th Aug 2019, 10:00 AM
Eugene Engineer
Eugene Engineer - avatar
4 Answers
+ 3
When n was 1, num was still a list, that's why 1 wasn't printed. statement "for n in lst" broken in iterations: n = "#" if type(n) == int: ~skip~ n = 1 if type(n) == int: #num = [] num = num.append(n) #num = None n = 2 if type(n) == int: #num = None num = num.append(n) #None.append(2)?, error raised.
26th Aug 2019, 10:07 AM
Seb TheS
Seb TheS - avatar
+ 2
append is a method from class 'list' and return None. In case of n = 1 (first integer of lst), then n is append to num but num is now None (because append returns None), so list num doesn't exist anymore. No error is raised so 1 isn't printed. For the two other integer, because num is None, it produces an error and print n. So output is 2 and 3.
26th Aug 2019, 10:18 AM
Théophile
Théophile - avatar
+ 1
#Sorry. For more readable must be: #Not print element from list lst = ["#",1,2,"4","a",3] num = [] for n in lst: if type(n) == int: print(n) #but there output is 1 2 and 3
26th Aug 2019, 10:05 AM
Eugene Engineer
Eugene Engineer - avatar
+ 1
Why this:......num = num.append(n)?? shouldn't it be just ......num.append(n) also:- Not sure why your using a try except block. Look up the builtin function isinstance().
26th Aug 2019, 10:53 AM
rodwynnejones
rodwynnejones - avatar