[Python] Type Error: Summary of error causes and remedies for'None Type'

[Python] Type Error:'NoneType' object is not iterable Cause and remedy

I was addicted to writing a recursive function, so how to deal with it.

Error that occurred


TypeError: 'NoneType' object is not iterable

In addition to the above, it is also useful for causing and dealing with all errors including "None Tpye".

Other error examples


・ Can only concatenate list(not "NoneType") to list
・ Can't multiply sequence by non-int of type 'NoneType'
・ Unsupported operand type(s) for +: 'NoneType' and 'list'
Such,,,

There are two conclusions.

** ① The execution result of the function without return is "Value None, Type None Type". ** **

** ② When assigning a function to a variable, the function must have a return. ** ** └ Not print. (Because it is not the execution result but one process in the middle of execution) └ return should be the final output of the function. └ It doesn't mean that you only need one return somewhere in the function.

Occurrence Status

Occurs when trying to extract an int from a multidimensional array.

error


arr0 = [1,[2],[[3]]]

def number(arr):
    result=[]
    
    if isinstance(arr, int):
        result.append(arr)
    
    if isinstance(arr, list):
        #Extract elements one by one
        for brr in arr:
            res = number(brr)
            result += res  #← This is an error
        return result
            
number(arr0)

#output
TypeError: 'NoneType' object is not iterable

## problem Caused by trying to mess with an object of'NoneType'.

** ▼ A little more detailed ** The function number () is assigned to the variable with "res = number (brr)", but since there is no return value in this function itself, None is stored in the variable and the type is NoneType.

"Result + = res" Because I tried to combine this NoneType variable res with the list type variable result.

It is said that res cannot be combined because it is not iterable.

What is NoneTpye?

An error that occurs when no default arguments are passed to the function. The value is None only.

What is (python official) None The only value of type NoneType. None is often used to indicate the absence of a value, such as when no default argument is passed to the function. The assignment to None is invalid and throws a SyntaxError.

** ▼ It looks like this ** When the execution result of the function is empty, the result itself becomes NoneType.

Therefore, if you assign a function whose execution result is empty to a variable, it becomes NoneType.

NoneTpye example


def hello():
    pass

x = hello()
print(type(x))
print(x)

#output
<class 'NoneType'>
None

#### Even in the case of print, it becomes None Type

None Type for print


def hello():
    print("Hello")

x = hello()
print(type(x))

#output
Hello
<class 'NoneType'>

It is output is "Hello", but one that is displayed in the execution process of the function, but does not replace the function itself.


### Remedy (installation of return) In order not to make it NoneType, return gives the function the actual condition. └ The return value replaces the result of executing the function with the function itself.

python


def hello():
    return ("Hello")

x = hello()
print(type(x))
print(x)

#output
<class 'str'>
Hello

x is replaced with the string "Hello".

Location of return

It doesn't mean that you only need one or more returns in a function. It is important that a return is returned as the final result of the execution.

▼ An example where return is described but becomes None Type

Example of becoming None Type


def hello(n):
    if n > 2:
        return ("Hello")

x = hello(1)
print(type(x))
print(x)

#output
<class 'NoneType'>
None

Since 1 <2, the output result of the function is empty. (Does not go through the return process)


▼ OK if the execution result goes through return

python


def hello(n):
    if n > 2:
        return ("Hello")

x = hello(3)
print(type(x))
print(x)

#output
<class 'str'>
Hello

## Supplement #### ▼ The type of the function itself is function

function


def hello():
    print("Hello")

print(hello)

#output
<function hello at 0x00000222AE142160>

▼ No parentheses required when assigning the function itself to a variable

Assign function


def hello():
    return ("Hello")

x = hello  #← No parentheses required
print(type(x))
print(x)

#output
<class 'function'>
<function hello at 0x00000222AE1423A0>

▼ Execution example of variable (assigning function)

python


def hello(n):
    if n > 2:
        return ("Hello")
    
x= hello
print(x(3))

#output
Hello

hello () = x ().


## Action result Corrected the error code described at the beginning.

** Set return appropriately so that the value assigned to the variable does not become a function. ** **

python


def number(arr):
    result=[]
    
    if isinstance(arr, int):
        result.append(arr)
    
    if isinstance(arr, list):
        #Extract elements one by one
        for brr in arr:
            res = number(brr)
            result += res
    return result  #← Set result as the return value of function number

It worked safely.

Recommended Posts

[Python] Type Error: Summary of error causes and remedies for'None Type'
Summary of Python indexes and slices
Correspondence summary of array operation of ruby and python
Summary of the differences between PHP and Python
Installation of Python3 and Flask [Environment construction summary]
I / O related summary of python and fortran
[Python] Class type and usage of datetime module
Summary of Python arguments
Summary of Python sort (list, dictionary type, Series, DataFrame)
Python --Explanation and usage summary of the top 24 packages
Summary of date processing in Python (datetime and dateutil)
Summary of python file operations
Summary of Python3 list operations
Python --Check type of values
Python data type summary memo
Source installation and installation of Python
[python] Summary of how to retrieve lists and dictionary elements
[Python] Summary of how to use split and join functions
Summary of Hash (Dictionary) operation support for Ruby and Python
Python error support note: "... does not support argument 0 of type float ..."
The story of Python and the story of NaN
Installation of SciPy and matplotlib (Python)
A brief summary of Python collections
[python] week1-3: Number type and operation
This and that of python properties
Summary of differences between Python and PHP (comparison table of main items)
Coexistence of Python2 and 3 with CircleCI (1.0)
Strange and horrifying Python error story
I'm not afraid of errors anymore! Python errors and their causes / solutions
Reputation of Python books and reference books
[OpenCV; Python] Summary of findcontours function
[Python] Summary of conversion between character strings and numerical values (ascii code)
Installation of Visual studio code and installation of python
[Python] Summary of how to use pandas
Extraction of tweet.js (json.loads and eval) (Python)
pix2 pix tensorflow2 Record of trial and error
Summary of various for statements in Python
[Python] Summary of array generation (initialization) time! !! !!
[Python] Understand the content of error messages
Connect a lot of Python or and and
[Python2.7] Summary of how to use unittest
[python] [meta] Is the type of python a type?
Summary of modules and classes in Python-TensorFlow2-
Summary of built-in methods in Python list
Summary of useful techniques for Python Scrapy
Summary of how to use Python list
Easy introduction of python3 series and OpenCV3
[Python] Various combinations of strings and values
[Python2.7] Summary of how to use subprocess
Python and NumPy numeric type inheritance relationship
Axis option specification summary of Python "numpy.sum (...)"
Idempotent automation of Python and PyPI setup
Full understanding of Python threading and multiprocessing
Python URL and query parameter parsing summary
[AWS] Summary of CLI installation error countermeasures
Project Euler # 1 "Multiples of 3 and 5" in Python
Python Summary
[Python] Create a list of date and time (datetime type) for a certain period
Python summary
[Python] How to use two types of type ()
Summary of how to import files in Python 3