Search code examples
pythonsortingfor-loopperfect-square

python 'int' object has no attribute 'sort'


Hey I am new to Python and I have this exercise I want to complete but I get the following error: 'int' object has no attribute 'sort'. I must use for-loop to take from a list of numbers and make them all square, then print them all out one by one as sorted. Did I use the sort command incorrectly? Or it doesen't even work with numbers? And do I have to use the .append() command to make them all print out one by one? So this is my wannabe code so far:

start_list = [5, 3, 1, 2, 4]
square_list = []
for square_list in start_list:
    square_list ** 2
print square_list.sort()

Solution

  • You must understand for loops.

    for square_list in start_list:
        square_list ** 2
    

    square_list in this example doesn't refer to the empty list you made. It is used as an ambiguous variable to extract values from a list. As such, this is just the each value in the list during each iteration, and they're all integers because that's what's in your list.

    Secondly, you're not actually appending the squares to the list, you're just calculating the squares and doing nothing with them. Lastly, the sort method doesn't return anything, it just alters the list without returning a value. Use the equivalent sorted method which doesn't alter the list but does return a new value. I think you'll best understand with some code.

    start_list = [5, 3, 1, 2, 4]
    square_list = []
    
    # for loop number is ambiguous variable
    
    for number in start_list: 
        square = number ** 2 # calculate square to add later
        square_list.append(square) # add the calculation
    
    print sorted(square_list) # print sorted version