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

Time:06-13

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.

CodePudding user response:

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.

CodePudding user response:

How about utilizing list.extend:

def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print('Error: Enter an integer, try again...')


def main() -> None:
    num_names = get_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']

CodePudding user response:

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...

  • Related