How to Sort Data in Python?

Estimated read time 1 min read

To sort data in Python, you can use the built-in sort() or sorted() functions. These functions can be used to sort a variety of data types, including lists, tuples, dictionaries, and more.

Here’s an example implementation:

# Define a list of data
my_list = [4, 2, 8, 1, 3, 9, 6]

# Sort the list in ascending order
my_list.sort()
print(my_list)  # Output: [1, 2, 3, 4, 6, 8, 9]

sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 2, 3, 4, 6, 8, 9]

In this example, we define a list my_list of integers. We use the sort() function to sort the list in ascending order, and then print the sorted list. We also use the sorted() function to create a new sorted list and print it.

If you want to sort data in descending order, you can pass the reverse=True argument to the sort() or sorted() function, like this:

# Sort the list in descending order
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 8, 6, 4, 3, 2, 1]

sorted_list = sorted(my_list, reverse=True)
print(sorted_list)  # Output: [9, 8, 6, 4, 3, 2, 1]

In this example, we sort the list of strings by their lengths using the len function as the sorting key.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply