pythonlistattributeerrortitlecapitalize

Mylist has an AttributeError when i was trying to capitalize it and find its length?


I want the following code to give me the title form and length of the list:

mylist = ['clean the keyboard', 'meet tom', 'throw the trash']
mylist.capitalize()

for index, item in enumerate(mylist):
    row = f"{index + 1}.{item}"
    print(row.title())
    print(len(row))

But instead of giving me the title of these todos and the length of the list it is giving me an attribute error.

This is the following error:

Traceback (most recent call last):
  File "C:\Users\tguru\Documents\todo_app\delete.py", line 2, in <module>
    mylist.capitalize()
    ^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'capitalize'

I expect the code to give me the list's length and the list's title version.


Solution

  • You cannot directly apply capitalize() on a list.

    It is a string method.

    capitalize()

    Instead you can do:

    mylist = ['clean the keyboard', 'meet tom', 'throw the trash']
    mylist = [x.capitalize() for x in mylist]
    #['Clean the keyboard', 'Meet tom', 'Throw the trash']
    

    Now, you can apply your method:

    for index, item in enumerate(mylist):
        row = f"{index + 1}.{item}"
        print(row.title())
        print(len(row))
    

    #Output

    enter image description here