0

I have the following for loop:

def validate(request, fields=None):
    i = 0
    j = len(fields)
    return_fields = []

    for f in fields:
        i += 1
        if request.data[f] != check_validity(f)
            if i == j:
                return_fields.append(f)
                return return_fields
            else:
                return_fields.append(f)

This checks the validity of the fields by some function check_validity(). If it is invalid, it appends it to the return_fields list and at the end, returns it to the main caller. My question is, in my code, I am using two variables i and j to just check if there are any elements left in the list 'fields'. But I am just wondering if there is a better way to do the same operation since I want to return all the invalid fields and not stop when I encounter any 1 of them.

Shrikant Kakani
  • 1,511
  • 2
  • 17
  • 37

4 Answers4

1

Another way is to use enumerate:

def validate(request, fields=None):
    return_fields = []

    for i, f in enumerate(fields):
        if request.data[f] != check_validity(f)
            if i+1 == len(fields):
                return_fields.append(f)
                return return_fields
            else:
                return_fields.append(f)

But i don't get it, why you need to know it? Why you can't just:

def validate(request, fields=None):
    for f in fields:
        if request.data[f] != check_validity(f)
            return_fields.append(f)
    return return_fields

Short form:

def validate(request, fields=None):
    return [
        f for f in fields
        if request.data[f] != check_validity(f)
    ]
KiraLT
  • 2,385
  • 1
  • 24
  • 36
0

A for loop automatically finishes when it's iterated all the way through an array, so you can just take the return out of the for loop and it'll run once all the elements in fields have been iterated through.

def validate(request, fields=None):
    return_fields = []

    for f in fields:
        if request.data[f] != check_validity(f)
            return_fields.append(f)
return return_fields
Yaiyan
  • 101
  • 7
0
def validate(request, fields=None):
    return_fields = []
    buggy = False
    for f in fields:
        if request.data[f] != check_validity(f)
            buggy = True
            return_fields.append(f)
    if buggy: return return_fields

BTW in your code, it will return return_fields only when last field is invalid.

Arovit
  • 3,579
  • 5
  • 20
  • 24
0

I guess using yield will be of use for you :) (take a look here What does the "yield" keyword do in Python? , it is relatively complex, but it is like a return without restarting the function)

def validate(request, fields=None):
   for f in fields:
        if request.data[f] != check_validity(f):
            yield (f)
Community
  • 1
  • 1
R. García
  • 43
  • 9