0
totalNum = int(input("No of people?"))
for i in range(1,totalNum+1):

    name_list = []
    name = input("Name?")
    name_list.append(name)
print(name_list)

In the end, when I tried to print all the elements in the list, only the last element was printed.

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
epiphany
  • 756
  • 1
  • 11
  • 29

2 Answers2

1

You need to create the list name_list = [] outside the loop, not every time within the loop:

Ps. with a little change to your range():

name_list = []

totalNum = int(input("No of people?"))
for i in range(totalNum):   
    name = input("Name?")
    name_list.append(name)
print(name_list)
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

The problem with your code is that you are re-initializing the list in every iteration and hence once the loop is done the last list is printed.

Here is the fixed version of the code

totalNum = int(input("No of people?"))
name_list = []
for _ in range(totalNum):
    name = input("Name?")
    name_list.append(name)
print(name_list)

Also note the use of _ here, it is a special throw away variable in python which you use if just need a dummy variable to loop over a sequence.

Also you don't need to initialize the range like range(1,totalNum+1), since python sequences always start from 0 you can do range(totalNum).

Rohit
  • 3,659
  • 3
  • 35
  • 57