The below is my code:
lst=list()
n= int(input())
for i in range(n):
s=input('Enter a String ')
v=lst.append(s)
print(v)
Why this following code returns none in print statement?
Many thanks in advance!!
The below is my code:
lst=list()
n= int(input())
for i in range(n):
s=input('Enter a String ')
v=lst.append(s)
print(v)
Why this following code returns none in print statement?
Many thanks in advance!!
The issue is when you do v = lst.append(s)
it returns none.
Solution:
lst=list()
n= int(input())
for i in range(n):
s=input('Enter a String ')
lst.append(s)
print(lst)
Moreover, this code can be written even shorter:
print([i for i in [input() for j in range(int(input()))]])
Your issue is that .append will not return the list that is being appended. None is being stored in v.
By simplifying, you can maybe prevent errors. This can be simplified like so:
print([input('Enter a string') for i in range(0, int(input('Enter a number')))])
This looks complicated, but is actually a shorthand version of a loop, called a List Comprehension. It is often used to create new lists. You can even add a condition to the end. Check it out!
new_list = [expression(i) for i in old_list if filter(i)]
or [i for i in i if i] if you want to sound funny!
There are three parts.
1.expression(i) is what is being added to the list each time it loops.
2.for i in old_list is your typical for loop.
3.Add an if to the end if you like!
Because this creates a new [list], you can return, print, or store in a variable.