More with 'for' - error "object of type" 'NoneType' has no len() (contains spoilers)



I've seen someone else post something similar to my code so I'm fairly certain it's correct however I'm getting an error with it that and I can't understand why.

start_list = [5, 3, 1, 2, 4]
square_list = []

# for loop to append squared number to square_list 
for number in start_list:
    square_list.append(number ** 2)

# sorts square_list, after the for loop has ran
square_list = square_list.sort()
print square_list

gives me:

Oops, try again.
Your code caused the following error: object of type 'NoneType' has no len()

Can someone shed some light please?

Trying to debug it I've added

print type(start_list)
print len(start_list)

above the loop and I receive <type 'list'> and 5 in the console.



Indentation issues really.

start_list = [5, 3, 1, 2, 4]
square_list = []

for x in start_list:
    square_list.append(x**2) #appending
    square_list.sort() #sorting
    print square_list

Hope the comment explains and this resolves! :slight_smile:


hey what did that code gives you plz ?



[9, 25]
[1, 9, 25]
[1, 4, 9, 25]
[1, 4, 9, 16, 25]



well it should give you this :slight_smile:
[1, 4, 9, 16, 25]
you should get rid of the indentation before print


hey bro the problem in your code is that you set #square_list.sort()# to a variable :wink:


Haha... I get your point.

I did that to help let the person who asked understand what really happens.

Thanks for that.

@ptibbetts, you might want to implement what @adn77790 just suggested. :slight_smile:


ohh, okay sorry for that i just wanted to get directly to the point it's a bit annoying to face such problems, it's better to get help as quickly as possible to keep coding :+1:



I was trying to be efficient and not run the sort() on every iteration of the for loop and didn't realise I had reassigned a list to a variable

thanks @adn77790!


You're welcome :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.