python Empty Tuple Returns Result Details in all

  • 2021-08-21 21:03:58
  • OfStack

We can put the object that needs to be judged in the program, and then there will be two results, either true or false. The all function we are going to talk about today is a program used to judge parameters, and outputs the results of True or False according to different input parameters. Let's explain the all function, understand the syntax and so on, and then discuss the return value result of empty tuples through examples.

1. Description:

Accept 1 iterator object as a parameter, and report an error when the parameter is null or not iterator object


>>> all(2) # Incoming value error report 
Traceback (most recent call last):
 File "<pyshell#9>", line 1, in <module>
  all(2)
TypeError: 'int' object is not iterable

Returns True if the logical value of each element in the iterable object is True, otherwise False


>>> all([1,2]) # The logical value of each element in the list is True , return True
True
>>> all([0,1,2]) # In the list 0 The logical value of is False , return False
False

Returns True if the iterable object is empty (number of elements is 0)


>>> all(()) # Empty tuple 
True
>>> all({}) # Empty dictionary 
True

2. Grammar


all(iterable) # iterable --  Tuples or lists. 

3. Parameters

iterable--Tuples or lists.

4. Return value

If all elements of iterable are not 0, ', False or iterable are empty, all (iterable) returns True, otherwise False;

5. Examples


>>> any(())
False
>>> any([])
False
>>> any(['',0])
False
>>> any(['',0,'1'])
True
>>> any(['',0,False])
False

Note: The return value of empty tuple and empty list is True, so special attention should be paid here.

How to handle empty (no) tuples returned from python function

I have a function that returns either 1 tuple or None. How should the caller handle this situation?


def nontest():
 return None

x,y = nontest()

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

EAFP:


try:
  x,y = nontest()
except TypeError:
  # do the None-thing here or pass

Or unless there is no attempt:


res = nontest()
if res is None:
  ....
else:
  x, y = res

Related articles: