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

Tyler Seymour picture Tyler Seymour · Dec 2, 2012 · Viewed 20k times · Source

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]

Answer

soulseekah picture soulseekah · Dec 2, 2012

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.