Flat_Eric getting tired of lists

List Methods Part 3

list_methods = [["part"] ['1', '2', '3']]
list_methods [0][0], [1][2]

List Methods Part 3: Organization & Order

Last list method lesson, I promise! If you are feeling overwhelmed, don't worry—these methods will become easier and easier as you use them. Soon, they will be tools that you reach for naturally whenever you need them.

The first method we are going to learn about today is .sort().

The .sort() Method: Lining Up Alphabetically

Imagine your movie theater line has become a mess. To make things organized, the manager asks everyone to line up in alphabetical order.

In Python, .sort() does exactly this. It look at the items in your list and rearranges them automatically.

How it works with Strings:

If you have a list of letters or names, .sort() puts them in A-B-C order.

How it works with Numbers:

If your list contains numbers, .sort() will arrange them from smallest to largest (ascending order).

.sort() vs. sorted()

The method vs the function.

In our movie theater analogy, .sort() is like the manager telling everyone in the actual line to move around and reorganize. But sorted() is like the manager taking a photo of the line and then rearranging the people in the photo, while the real people stay exactly where they were.

  1. The .sort() Method (The "Mover")
    • In-place: It physically changes the original list.
    • Return Value: It returns None.
  2. The sorted() Function (The "Photographer")
    • Not in-place: It leaves the original list alone.
    • Return Value: It creates a brand new sorted list that you can save to a variable.
      1. Print numbers.
      2. Print new_numbers.

When to use which?

Feature .sort() sorted()
Original List Changed forever. Stays the same.
Result Returns None Returns a new sorted list.
Storage Use when you don't need the old order anymore. Use when you want to keep the original order for later.

The .reverse() Method

Finally, we have .reverse(). This is different from sorting. It doesn't care about the alphabet or numbers; it simply flips the list upside down. The person at the back is now at the front.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Alphabetical Order

The movie theater manager wants the guest list organized alphabetically to make check-in easier.

Exercise 2: The "Safe" Sort (sorted)

You want to see what the list would look like sorted, but you need to keep the original arrival order for your records.

Exercise 3: Reverse Alphabetical

The theater decides to board the plane from Z to A.

Exercise 4: Flip the Line

The manager announces that the person at the back of the line is now the first person to enter!

Exercise 5: The "None" Trap

This exercise demonstrates a common mistake students make with in-place methods.

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course