Working with lists in python

I wonder if sorting works with .sort() or sorted() on a list with different data types exist
For example see the list called ap

Ref: Exercise

ap = ["Kareem", 1969, "Fatima", 1975, "Rauoof", 1988, "Noor", 1995, "Musawir", 2000, "Safwa", 1997, "Iyan", 2017, "Jaseera" ,2003]
print(ap)
sorted_ap = sorted(ap)
print(sorted_ap)

It gives me the following error.

[‘Kareem’, 1969, ‘Fatima’, 1975, ‘Rauoof’, 1988, ‘Noor’, 1995, ‘Musawir’, 2000, ‘Safwa’, 1997, ‘Iyan’, 2017, ‘Jaseera’, 2003]

Traceback (most recent call last):
** File “C:\Users\user\Desktop\Learning\July2021\31072021.vscode\MyCodingBegins.py”, line 22, in **
** sorted_ap = sorted(ap)**
TypeError: ‘<’ not supported between instances of ‘int’ and 'str’

Try:
https://docs.python.org/3/howto/sorting.html

and:
https://realpython.com/python-sort/#lists-with-non-comparable-data-types-cant-be-sorted

Thanks, the second URL shows. It straight forward. ‘we cannot do it in that way’

Yea, you can’t use both string and int types of data with that method.

It’s also good to read the official documentation too. :slight_smile:

1 Like