Abhilasha Tripathi
Abhilasha Tripathi

Reputation: 31

Can we take multiple inputs and then append it in one list?

I am trying to make a program which will take multiple inputs from a user of names and append it into a list. The names will have surnames and I have to split the surnames and make all the inputs in one list like- ['Christiano', 'Ronaldo','Harry','Potter', 'Lionel', 'Messi'} I tried using the split function but it only gives the list of the last input. I tried appending it but it makes it a list of list. Please help.Here's my code-

inp = int(input("Enter the no.of names"))

for i in range(inp):
    name = input("Enter the names").split(" ")

print(name)

Here, as you can see, the split function is only splitting and giving me the list of last name, not the other names.

Upvotes: 0

Views: 169

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22370

How about utilizing list.extend:

from typed_input import int_input  # pip install typed_input

def main() -> None:
    num_names = int_input('Enter the no. of names: ')
    names = []
    for i in range(1, num_names + 1):
        name = input(f'Enter name {i} of {num_names}: ')
        names.extend(name.split())
    print(f'{names = }')

if __name__ == '__main__':
    main()

Example Usage:

Enter the no. of names: 3
Enter name 1 of 3: Christiano Ronaldo
Enter name 2 of 3: Harry Potter
Enter name 3 of 3: Lionel Messi
names = ['Christiano', 'Ronaldo', 'Harry', 'Potter', 'Lionel', 'Messi']

Upvotes: 1

d r
d r

Reputation: 7786

Or just like this ...

inp = int(input("Enter the no.of names --> "))
lst = []
for i in range(inp):
    name = input("Enter the names --> ").split()
    for x in range(len(name)):
        lst.append(name[x])
print(lst)

""" R e s u l t
Enter the no.of names --> 3
Enter the names --> aa bb
Enter the names --> cc dd ee
Enter the names --> ff gg
['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
"""

... as a mild correction of your code. Regards...

Upvotes: -1

s3dev
s3dev

Reputation: 9701

The list of names can be extended as follows:

names = []
for _ in range(inp):
    names.extend(input('Enter name: ').split(' '))

The .extend() function adds the values of the split names list, to the end of the names list.

Python list tutorial documentation linked here.

Upvotes: 1

Related Questions