Reputation: 31
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
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
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
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