[Tutor] AttributeError,

Steven D'Aprano steve at pearwood.info
Wed Aug 12 04:01:45 CEST 2015

On Tue, Aug 11, 2015 at 04:24:39PM -0700, Ltc Hotspot wrote:
> Hi Everyone,
> Why is there an AttributeError, line 12, below : 'tuple' object has no
> attribute 'sort'?

Haven't I see this exact same question, complete with solutions, on the 
python-list mailing list? 

The answer found there is that you are trying to sort the wrong value. 
You are trying to sort an immutable (that is, unchangeable) (key, value) 
tuple, which includes one string and one number. And then you ignore the 
sorted result!

You have:

    ncount = (key,val)
    print key,val

Sorting (key, val) cannot work, because that is an immutable tuple. 
Turning it into a list [key, val] now makes it sortable, but that 
doesn't do what you want: Python 2 always sorts ints ahead of strings, 
regardless of their actual values. But even if you did meaningfully sort 
the list [key, val], having done so you don't look at the results, but 
print the key and val variables instead, which are unchanged.

Changing the order of items in a list does not, and can not, change the 
variables that were used to build that list.

If that is not clear, study this example:

py> a = 999
py> b = 1
py> alist = [a, b]  # construct a list from a and b
py> print alist
[999, 1]
py> alist.sort()  # change the order of items in the list
py> print alist
[1, 999]
py> print a, b  # have a and b changed?
999 1

The actual solution needed is, I think, sorting the entire collection:

items = sorted(count.items())
for key, val in items:
    print key,val


More information about the Tutor mailing list