Coding with AI

Code Faster. Think Smarter. Ship Better—with AI.

Stop fighting boilerplate and busywork. Coding with AI shows professional Python developers how to use AI tools to accelerate design, coding, testing, debugging, and documentation—without sacrificing quality or control. Learn proven prompts, real workflows, and practical techniques you’ll use on the job every day.

Explore the book ->


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.

Coding with AI

AI Is Changing Software Development. This Is How Pros Use It.

Written for working developers, Coding with AI goes beyond hype to show how AI fits into real production workflows. Learn how to integrate AI into Python projects, avoid hallucinations, refactor safely, generate tests and docs, and reclaim hours of development time—using techniques tested in real-world projects.

Explore the book ->