Why using list() inside a loop return memory error in Python 3.x?

Viewed 182

I got the following piece of code:

var = []
for i in range(0,len(code_list)-11):
        
        sorted_list = sorted(code_list[i:i+10]) 
        minmax_list = list(range(min(sorted_list), max(sorted_list)+1))
        
        if (sorted_list == minmax_list):
            var = var+lista_ordenada

When the code_list is so large a memory error return. However, when replacing for the following:

var = []
for i in range(0,len(code_list)-11):
        
        sorted_list = sorted(code_list[i:i+10]) 
        minmax_list = np.arange(min(sorted_list), max(sorted_list)+1, 1).tolist()
        
        if (sorted_list == minmax_list):
            var = var+lista_ordenada

The routine ends successfully. Does anyone know the reason?

Thanks in advance!

1 Answers

tolist() will convert all the data to python standard library types. It also knows it is a numpy array and has access to highly optimized backing array.

list just uses an iterator to add all the elements so is much slower and more memory intensive.

Related