Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't sort my list because it is NoneType? Simple Python

I get this error when I try to figure out the low and high prices for my BeautifulSoup web scraper. I attached the code below. Shouldn't my list be a list of ints?

I went through the similar NoneType questions before posting this, but the solutions did not work (or maybe I didn't understand them!)

Traceback (most recent call last):
  File "/home/user-machine/Desktop/cl_phones/main.py", line 47, in <module>
    print "Low: $" + intprices[0]
TypeError: 'NoneType' object is not subscriptable

Relevant Snippet:

intprices = []
newprices = prices[:]
total = 0
for k in newprices:
    total += int(k)
    intprices.append(int(k))

avg = total/len(newprices)

intprices = intprices.sort()

print "Average: $" + str(avg)
print "Low: $" + intprices[0]
print "High: $" + intprices[-1]
like image 655
Tyler Seymour Avatar asked Dec 02 '12 09:12

Tyler Seymour


People also ask

Why is Python saying my list is NoneType?

Sometimes this error appears when you forgot to return a function at the end of another function and passed an empty list, interpreted as NoneType.

How do I change NoneType to list?

Use the syntax new_value if value is None else value to replace None with the new_value if the statement value is None evaluates to True otherwise keep the same value . For a more compact solution, use the syntax value or new_value to use the new_value as the replacement for None since None is considered False .

How do I sort a list permanently in Python?

Lists can be sorted using two methods, the sort() and the sorted() method. The former permanently sorts the list whereas sorted() is used to sort the list temporarily.

Why the sort function is returning none in Python?

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value. So problem is with answer = newList. sort() where answer is none. Instead you can just do return newList.


2 Answers

intprices.sort() is sorting in place and returns None, while sorted( intprices ) creates a brand new sorted list from your list and returns it.

In your case, since you're not wanting to keep intprices around in its original form simply doing intprices.sort() without reassigning will solve your issue.

like image 84
soulseekah Avatar answered Sep 24 '22 14:09

soulseekah


Your problem is the line:

intprices = intprices.sort()

The .sort() method on a list operates on the list in-place, and returns None. Just change it to:

intprices.sort()

like image 42
wim Avatar answered Sep 20 '22 14:09

wim