The Power of Built-In Functions in Python for Beginners

Python offers several ways to sort data, including built-in functions that are highly efficient and can handle complex scenarios. In this tutorial, we’ll discuss sorting lists alphabetically using the …

Updated October 8, 2023

Python offers several ways to sort data, including built-in functions that are highly efficient and can handle complex scenarios. In this tutorial, we’ll discuss sorting lists alphabetically using the sorted() function in Python.

Sorting Lists Alphabetically

In Python, you can easily sort a list of strings or numbers by using the sorted() function. Here is an example of how to use it:

fruits = ['apple', 'banana', 'cherry']
sorted_fruits = sorted(fruits)
print(sorted_fruits)

This will output ['apple', 'banana', 'cherry'].

You can also sort a list in reverse order by using the reverse parameter:

fruits = ['apple', 'banana', 'cherry']
sorted_fruits = sorted(fruits, reverse=True)
print(sorted_fruits)

This will output ['cherry', 'banana', 'apple'].

Sorting Strings in a List of Dictionaries

Let’s say we have a list of dictionaries where each dictionary represents a product and the key-value pairs represent properties. Here is an example:

products = [{'name': 'Apple', 'price': 10}, {'name': 'Banana', 'price': 20}, {'name': 'Cherry', 'price': 15}]
sorted_products = sorted(products, key=lambda x: x['name'])
print(sorted_products)

This will output [{'name': 'Apple', 'price': 10}, {'name': 'Banana', 'price': 20}, {'name': 'Cherry', 'price': 15}].

Using Sort() Method in a Loop

You can also sort a list by using the list.sort() method within a loop:

fruits = ['banana', 'apple', 'cherry']
for i in range(len(fruits)):
    for j in range(i+1, len(fruits)):
        if fruits[i] > fruits[j]:
            fruits[i], fruits[j] = fruits[j], fruits[i]
print(fruits)

This will output ['apple', 'banana', 'cherry'].

Remember, when working with more complex sorting scenarios, it may be beneficial to use the sorted() function combined with the list.sort() method instead of looping to sort lists in Python.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp