It works because I use the lil format. When I did this code, I tried to return a dense matrix whend X was dense and a sparse matrix when X was sparse. I agree with you, it's a big waste to do that if the zeros are imputed. I'll add a new if above this one to solve the problem.