![]() |
List problem "TypeError: must be str, not int" - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List problem "TypeError: must be str, not int" (/thread-7874.html) |
List problem "TypeError: must be str, not int" - RedSkeleton007 - Jan-28-2018 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() 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? RE: List problem "TypeError: must be str, not int" - j.crater - Jan-28-2018 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. |