Skip to content

ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ

List methods and sorting

3 min read

A shopping list grows while you shop and shrinks as you buy things. In this lesson you'll add and remove items, sort a list two different ways, and learn the one rule that explains the most common list bug: the methods that change a list return None, not the list.

Adding and removing

A list comes with its own tools. You call them with a dot after the list: cart.append("coffee"). A tool that belongs to a value like this is a . These four change the list they're called on:

cart = ["teff", "onions"]
cart.append("coffee")
cart.insert(0, "sugar")
print(cart)
cart.remove("onions")
last = cart.pop()
print(last)
print(cart)

In the editor, press Escape then Tab to move on.

  • append(x) adds x at the end.
  • insert(i, x) puts x at position i and moves the rest along.
  • remove(x) takes out the first item equal to x.
  • pop() takes out the last item and returns it, so last is "coffee".

Printing a list shows its text items in quotes, so you can see where each one starts and ends. Add "salt" to the cart and run it again.

What does remove() do when the value appears twice?

ጥያቄ

After nums = [5, 2, 7, 2] and nums.remove(2), what is nums?

Removing something that isn't there is an error:

One item, or several

append and extend both add to the end. Predict the difference.

ውጤቱን ገምቱ

Decide before you look. Guessing wrong is how this sticks.

a = [1, 2]
a.append([3, 4])
b = [1, 2]
b.extend([3, 4])
print(a)
print(b)
Pick the output

Python prints

[1, 2, [3, 4]]
[1, 2, 3, 4]

append adds exactly one item, whatever it is: here, a whole list, so a ends with a list inside it and has 3 items. extend adds each item of the list you give it, so b has 4.

Changing methods return None

sort() puts a list in order. Here's a way people often use it. Predict what it prints.

ውጤቱን ገምቱ

Decide before you look. Guessing wrong is how this sticks.

nums = [30, 10, 20]
nums = nums.sort()
print(nums)
Pick the output

Python prints

None

nums.sort() sorts the list and returns None. Then nums = ... moves the name to that None, and the sorted list is lost.

None is Python's "nothing" value from lesson 2.4. The rule: a method that changes a list returns None. That's true of append, insert, remove, extend, and sort. (pop is the one exception: it returns the item it took out.) Call them on their own line, and don't give what they return a name. The bug usually shows up a line later:

sort() and sorted()

There are two ways to sort. sorted() makes a new sorted list and leaves the original alone. .sort() changes the list itself. Both take reverse=True for largest first.

scores = [67, 82, 45]
ranked = sorted(scores)
print(ranked)
print(scores)
scores.sort(reverse=True)
print(scores)

In the editor, press Escape then Tab to move on.

Use sorted() when you still need the original order, .sort() when you don't. Text sorts too, but predict this one:

ውጤቱን ገምቱ

Decide before you look. Guessing wrong is how this sticks.

print(sorted(["banana", "apple", "Cherry"]))
Pick the output

Python prints

['Cherry', 'apple', 'banana']

Python sorts text by character codes, and every capital letter comes before every small letter. So Cherry comes first.

To sort the way a dictionary does, ignoring case, give sorted a key: a way to turn each item into what should be compared. key=str.lower compares the lowercase version of each word, but keeps the words as they were. Module 5 explains key fully.

print(sorted(["banana", "apple", "Cherry"], key=str.lower))

In the editor, press Escape then Tab to move on.

The collect plan

Very often you build a list as you go: start with an empty list, [], and append inside a loop. This is the collect plan. Here it collects every price over 100 birr:

prices = [250, 40, 1200, 85]
expensive = []
for price in prices:
    if price > 100:
        expensive.append(price)
print(expensive)

In the editor, press Escape then Tab to move on.

Like a running total, the empty list goes before the loop. Change it to collect the prices under 100.

መልመጃ

Telebirr amounts

Read Telebirr amounts, one per line, until the user types 0. Collect them in a list, then print the list sorted from largest to smallest.

Your code

amounts = []
# Read amounts until 0, collect them, then print them largest first

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

amounts = []
while True:
    amount = int(input("Amount: "))
    if amount == 0:
        break
    amounts.append(amount)
print(sorted(amounts, reverse=True))

ዋና ዋና ነጥቦች

  • A method is a tool that belongs to a value: cart.append("coffee").
  • append, insert, remove (first match only), and pop change a list; append adds one item, extend adds each item.
  • Methods that change a list return None, so never write nums = nums.sort().
  • sorted() makes a new list; .sort() changes the list. Capitals sort first unless you use key=str.lower.
  • The collect plan: start with [] before the loop, append inside it.