1

I am trying to pass 10 inputs(names) into a list in python but I am getting one list element only take a look!

I tried to do this, but didn't work!

my problem is just at passing the inputs into a list i tried a lot but cant seem to find a solution, please help me with this

for inputs in range(0, 10):
    names=input("enter names: ")
    
students= []
students.append(names)
print(students)

but the output I am getting is: ['example name']

What should I do?

1
  • You need to initialize list before loop and append value every iteration. Commented Oct 12, 2020 at 11:34

4 Answers 4

2

First you should make a list. Then get inputs 10 times and append them into the list ten times. (One name each time)

students = []
for i in range(10):
    name = input("enter one name: ")
    students.append(name)
print(students)

Or you can have this inline version:

students = [input("enter one name: ") for i in range(10)]
print(students)

If you want to input all the names in one input, suppose that you seperate the names with , character, as much as you want:

students = input("enter names: ").split(',')
Sign up to request clarification or add additional context in comments.

2 Comments

Your welcome. Please consider confirming the answer @BakkarBakkar
The second approach "delimited input" (CSV) is very intuitive and one-shot easy.
1

This should help you:

students= []
for inputs in range(0, 10):
    name=input("enter name: ")
    students.append(name)
print(students)

2 Comments

oh thanks it worked can you tell me how the order changed everything please, again thank you
It is because u assign the input to the var names every time. U just Assign it, u don't Append it to any list. So if the name is 'a' the first time, if u enter 'b' the second time, the name would turn into b. To summarize, when u just use name=input("enter name: "), the existing value is overwritten by the newly entered value.
1

you are overriding you own value of names in the for loop, and then insert it only once, after the loop, to the list. append should be in the loop

students= []
for inputs in range(0, 10):
    names=input("enter names: ")
    students.append(names)
    
print(students)

Comments

1

The names variable is a variable, not a list... So with every input, it replaces the text that u entered before. To fix this just instantly append them;

students= []
for inputs in range(0, 10):
    students.append(input("enter name: "))
    
print(students)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.