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


#1

Hey,

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.

:confused:


#3

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:


#4

hey what did that code gives you plz ?


#5

This:

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

:slight_smile:


#6

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


#7

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


#8

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:


#9

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:


#10

facepalm

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!


#11

You're welcome :slight_smile:


#12

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