Home > Net >  Getting more on each iteration for list.append
Getting more on each iteration for list.append

Time:11-17

I've written a code to let user continuously input for new members' name for Beatles and print the a new list of members' name once user has done with inputting, but i keep getting repeated names if i entered more than one name. Could somebody help me out here?

Attached the code below. Many thanks!

# step 1
beatles = ['John Lennon', 'Paul_McCartney', 'Geogre Harrison']

new_list=[]
new_member = ''
while True:
    new_member = input ('Please enter new memebers to the group, enter NA to exit entering: ')
    if new_member == 'NA':
        break
    else:
        new_list.append (new_member)
        for i in new_list:
            beatles.append(i)
print("Step 3:", beatles)

CodePudding user response:

two solution

1:

for i in new_list:
    if i not in beatles:
        beatles.append(i)

or you don't need new_list at all

2: after else

beatles.append(new_member)

CodePudding user response:

You should set new_member empty and define new_list each time the code runs you can make some changes as i done in you code and it will run while giving you the desired output.

beatles = ['John Lennon', 'Paul_McCartney', 'Geogre Harrison']

while True:
    new_list=[]
    new_member = ''
   
    new_member = input ('Please enter new memebers to the group, enter NA to exit entering: ')
   
    if new_member == 'NA':
        break
    else:
        new_list.append (new_member)
    for i in new_list:
        beatles.append(i)
   
    print("Step 3:", beatles)
  • Related