pythonarraysloopsarraylist

Looping if statement


I want to loop through an array with an if statement and only after it has looped through the entire array execute the else.

This is how i have my code now

for index, nameList in enumerate(checkedName)
    if record["first_name"] == nameList["first_name"] and record["last_name"] == nameList["last_name"]:
        print("Match name")
    else:
        print("No match name")
        checkedName.append({"id" : record["id"], "first_name" : record["first_name"], "last_name" : record["last_name"]})

But i would like it to be more like this:

for index, nameList in enumerate(checkedName) if record["first_name"] == nameList["first_name"] and record["last_name"] == nameList["last_name"]:
    print("Match name")
else:
    print("No match name")
    checkedName.append({"id" : record["id"], "first_name" : record["first_name"], "last_name" : record["last_name"]})

But i have no idea how to do this in a not so messy way i have an idea but i feel like i could do this shorter


Solution

  • Using any() is more pythonic and readable...Logic is like check if any record in the list matches your conditions

    if any(record["first_name"] == nameList["first_name"] and 
           record["last_name"] == nameList["last_name"] 
           for nameList in checkedName):
        print("Match name")
    else:
        print("No match name")
        checkedName.append({
            "id": record["id"], 
            "first_name": record["first_name"], 
            "last_name": record["last_name"]
        })