Print("Sorted List B based on index 1: % s" % (sorted(B, key=itemgetter(1)))) Print("Sorted List A based on index 0: % s" % (sorted(A, key=itemgetter(0))))ī =, , ] Therefore, the function sorted(List_name, key=itemgetter(index_number)) sorts a list of lists by the element positioned at the specified index_number of each inner list.įor example, from operator import itemgetter The function itemgetter() from the operator module takes an index number as a parameter and returns the element from the data set placed at that index number. By default, it sorts the list in ascending order. The function sorted() is used to sort a list in Python. Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python In this tutorial, we will sort a list of lists in Python based on some indexes. Sorting a list of lists arranges all the inner lists according to the specified index as the key. These can be thought of as a list of lists. We can sort a list in Python by arranging all its elements in ascending or descending order based on the requirement. Use the sort() Function to Sort a List of Lists in PythonĪ list is one of the most powerful data structures used in Python.Use the lambda Expression Along With the sorted() Function to Sort a List of Lists in Python.Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |