Bakkar Bakkar
Bakkar Bakkar

Reputation: 64

Passing Inputs into a list in python

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?

Upvotes: 1

Views: 478

Answers (4)

user14310923
user14310923

Reputation:

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)

Upvotes: 1

F.NiX
F.NiX

Reputation: 1505

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(',')

Upvotes: 2

Nir Levy
Nir Levy

Reputation: 12953

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)

Upvotes: 1

Sushil
Sushil

Reputation: 5531

This should help you:

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

Upvotes: 1

Related Questions