Getting more on each iteration for list.append

Question:

I’ve written a code that lets the user continuously input new members’ names for The Beatles, and prints a new list of members’ names once the user has done with inputting, but I keep getting repeated names if I enter more than one name.

Could somebody help me out here?

# step 1
beatles = ['John Lennon', 'Paul McCartney', 'George 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)
Asked By: MING YANG

||

Answers:

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)

Answered By: Hossein Asadi

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)
Answered By: unleashed gamer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.