ignore in function call if empty

Asked

Viewed 245 times

2

suppose I feed a function with a tuple:

a = ['c:/', 'd:/', 'x:/', 'y:/']
b = ['c:/data', 'd:/data']
funcao((a, b))

however if you have an empty list you would like it to be ignored as an example:

funcao((se_vazio_ignore(a), se_vazio_ignore(b)))

it is possible to do this?

2 answers

1

If a list is empty, and the function is to use the list elements, you do not need to do and - the body of the for which will use the list will simply not be executed.

def funcao(x):
   for lista in x:
       for elemento in lista:
           # fazer coisas

funcao((a, b))

Okay, in case "a" is an empty list forinternal simply will not be executed.

In other situations you may want to run some other value in case your variable is an empty list, or None, or other false value. In this case, you can use the operator’s "short Circuit" or - in the same way that it is used in lignuances with the syntax derived from C (which they use || as an operator of "or").

Suppose your variable "a" or 'b" could have the value None. In this case, they could not be used directly on for: would make a mistake by saying that None is not interoperable :

funcao((a or [], b or []))

(to call the same function above, ensuring that each of the elements is eternal).

1


If I understand, something like this already resolves:

if len(a) > 0 and len(b) > 0:
    funcao((a, b))

EDIT

In fact you also need to check if any of the elements is not null:

if len(a) > 0 and len(b) > 0 and all(e != '' for e in a) and all(e != '' for e in b):
    funcao((a, b))
  • then did not solve because an empty list as list = ['''] if you use Len(list) will return you the size of 1.

  • I edited the answer.

  • 1

    In Python an empty jpá list has false boolean value - no need to write if len(a) > 0 only if a

Browser other questions tagged

You are not signed in. Login or sign up in order to post.