Search code examples
python-3.xlistpython-3.6

Is there any way to sort a python list by length (longest string first?)


I need to sort my list comprised of variables created through a class by their name (ex. var.name).

I have tried the .sort(key=len, reverse=True) method but it returns this error:

Traceback (most recent call last):
  File "/home/runner/TPF-Tests/main.py", line 92, in <module>
    newvar=shop(1,possibleplace, 70, inventory)
  File "/home/runner/TPF-Tests/main.py", line 64, in shop
    itemlist.sort(key=len, reverse=True)
TypeError: object of type 'item' has no len()

I am a beginner so explanations would be greatly appreciated.


Solution

  • Your sort key (key=len) doesn't make any sense. You need to sort on the length of the item.name attribute:

    mylist.sort(key=lambda x: len(x.name), reverse=True)
    

    For example:

    import dataclasses
    
    @dataclasses.dataclass
    class item:
        name: str
    
    
    mylist = [
        item(name='bob'),
        item(name='alice'),
        item(name='mallory'),
        item(name='mallory'),
        item(name='david'),
        item(name='chuck'),
            ]
    
    
    mylist.sort(key=lambda x: len(x.name))
    print(mylist)