简体   繁体   中英

how can I solve TypeError: 'NoneType' object is not iterable in pyhton

import pyfiglet
pyfiglet.print_figlet("Niko CyMax",'puffy')

num_list=[ (1,2) , (3,1000) , (5,6) , (9,10) , (8,500) , (70,400) ]

num_list_manual_sort=num_list.sort()
num_list_pro_sort=num_list.sort(key = lambda x: x[1])

for i in num_list_manual_sort:
    print(i)

for i in num_list_pro_sort:
    print(i)

and error is:

TypeError: 'NoneType' object is not iterable

Sorting a list with sort() changes the list in place , that means, the list num_list is changed directly, instead of the sorted list being returned and the original one left intact. You want to use the builtin sorted function, which does exactly what you want:

import pyfiglet
pyfiglet.print_figlet("Niko CyMax",'puffy')

num_list=[(1, 2), (3, 1000), (5, 6), (9, 10), (8, 500), (70, 400)]

num_list_manual_sort = sorted(num_list)
num_list_pro_sort = sorted(num_list, key=lambda x: x[1])

for i in num_list_manual_sort:
    print(i)

for i in num_list_pro_sort:
    print(i)

When you are sorting a list with sort method, you are changing the list itself, and None is returned.

num_list_manual_sort=num_list.sort()
num_list_pro_sort=num_list.sort(key = lambda x: x[1])

Both num_list_manual_sort and num_list_pro_sort will hold None . In case you want to get the list back, you can replace it by:

num_list.sort()
num_list_manual_sort = num_list[:]
num_list.sort(key = lambda x: x[1])
num_list_pro_sort = num_list[:]

There are more options for doing that, depends on your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM