Python Forum

Full Version: List problem "TypeError: must be str, not int"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to print the elements of a list of strings to test Python's sorting methods, but it's complaining about data types:
#!/usr/bin/env python3
#ListSorting.py

def stringListSort():
    upperAndLowerSort = ["chicken", "pig", "Dink", "cow"]
    upperAndLowerSort.sort()
    for i in upperAndLowerSort:
        print(str(i))#print(upperAndLowerSort[i])
        i += 1
    keyArgSort = ["chicken", "pig", "Dink", "cow"]
    keyArgSort.sort(key=str.lower)
    for i in keyArgSort:
        print(i)
        i += 1

def main():
    stringListSort()

main()
Error:
========= RESTART: I:/Python/Python36-32/SamsPrograms/ListSorting.py ========= Dink Traceback (most recent call last): File "I:/Python/Python36-32/SamsPrograms/ListSorting.py", line 19, in <module> main() File "I:/Python/Python36-32/SamsPrograms/ListSorting.py", line 17, in main stringListSort() File "I:/Python/Python36-32/SamsPrograms/ListSorting.py", line 9, in stringListSort i += 1 TypeError: must be str, not int >>>
I understand that I'm not printing integer elements, but how do I get it to print the string elements via their list index?
And why is "Dink" the only thing printing out before generating an error?
The i variable in for loop is not the index but rather a particular item from your list, over which it iterates. Try this:

my_list = ['a','b','c','d']
for item in my_list:
    print(item)
If you want to get index in each loop, you need to use enumerate() function, like this:

my_list = ['a','b','c','d']
for index, item in enumerate(my_list):
    print(index, item)
Quote:And why is "Dink" the only thing printing out before generating an error?
Now you probably understand why this happens. Line #8 gets executed properly before hitting the error in line #9. You print first item in the list, which is a string anyway.