Home > Back-end >  Renew list for every iteration
Renew list for every iteration

Time:12-04

I want to renew the "namelist" for each iteration and use "if" to compare "name" against "namelist". The first iteration will always replace the content of "namelist" because the "namelist" at the first iteration is empty. For iteration number x, I therefore want "name" to be compared with the list's content from the previous iteration, ie x - 1. I do not want to append "name" to "namelist" but replace the entire content so the comparison is always between "name" and the latest version of "namelist". The "#-line" in the code shows where I think the operator should be.

def loop():
    namelist = []
    a = 1
    while a < 5:
        name = input("enter your name")
        if name != namelist:
            # operator that replaces the contents of "name list" with "name"
        else:
            continue
        a  = 1

loop()

CodePudding user response:

I'm not sure if I understand what you want to do, but when you do if name != namelist you are comparing a string with a list, if you want to compare name with something inside namelist you should do if name not in namelist (literally asking if its not in the list) or if name != namelist[0] (asking if its different from the first element of the list)

And I think the operation you want to do can be achieved by doing namelist = [name] (just redefining the list)

  • Related