Why it is showing none? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why it is showing none?

d = int(input()) s = [] h = [s.append(i) for i in range(1,d+1)] print(h) The result of the code showing none..what is the reason?

8th Mar 2023, 4:24 PM
Dhrubak
4 Answers
+ 11
s.append(i) does not return anything, so it returns None. Print s and see the difference.
8th Mar 2023, 4:27 PM
Lisa
Lisa - avatar
+ 12
Dhrubak > (1) when using a *list comprehension*, we do not need to use append(), since it creates a new list and adds the values to it. inp = int(input()) res = [num for num in range(1, inp + 1)] # (1) print(res) #we should also use meaningful names for variables and other objects.
8th Mar 2023, 6:35 PM
Lothar
Lothar - avatar
+ 1
Thank you
8th Mar 2023, 4:41 PM
Dhrubak
0
The reason you are seeing None printed to the console is because the list comprehension used to create the list h is not meant to return a value, but instead is meant to perform an action. Specifically, the list comprehension is appending each integer from 1 to d to the list s. Since the list comprehension does not return a value, the value of h is simply the return value of the append() method, which is None. Therefore, when you print h, you see None printed to the console. To fix this issue, you can simply create the list h using the following code: d = int(input()) h = list(range(1, d+1)) print(h) This creates a list h containing the integers from 1 to d, using the list() function and the range() function. When you print h, you will see the expected output, which is the list of integers from 1 to d.
10th Mar 2023, 1:58 PM
Frensam Tabigne
Frensam Tabigne - avatar