Skip to content

Beginner · Lists, tuples, dictionaries and sets · topic 14 of 50 · 25 min

List methods and slicing

Explanation

Lists have methods that change them: append, insert, extend, remove, pop, sort and reverse. Slicing like marks[1:3] takes a part of a list as a new list. Be careful: b = a does not copy a list, it gives the same list a second name; use a.copy() for a real copy.

Methods: actions that belong to a list

A method is a function that belongs to a value. You call it with a dot after the value, like cart.append("rice"). Lists come with many useful methods, and most of them change the list itself.

python
cart = ["rice", "dal"]
cart.append("oil")
cart.insert(0, "salt")
print(cart)
append adds at the end. insert(0, ...) puts an item at index 0, the front. Shows ['salt', 'rice', 'dal', 'oil'].
python
cart = ["rice", "dal"]
cart.extend(["sugar", "tea"])
print(cart)
cart.remove("dal")
last = cart.pop()
print(last, cart)
extend adds every item of another list. remove deletes the first matching value. pop() removes the last item and gives it back: tea.

index(value) tells you where a value first appears, and count(value) tells you how many times it appears. pop(i) with an index removes the item at that position.

python
votes = ["tea", "coffee", "tea", "lassi", "tea"]
print(votes.index("coffee"))
print(votes.count("tea"))
Shows 1, then 3.
Careful: remove("x") and index("x") give a ValueError if "x" is not in the list, so check first with if "x" in my_list. Also, append(["a", "b"]) adds the whole list as ONE item; use extend to add the items one by one.

Sorting: sort() versus sorted()

my_list.sort() sorts the list in place, which means it changes the list itself, and it returns None. sorted(my_list) leaves the original alone and gives you a new sorted list. Add reverse=True to sort from biggest to smallest. my_list.reverse() simply flips the order.

python
marks = [65, 91, 78]
ranked = sorted(marks, reverse=True)
print(ranked)
print(marks)
marks.sort()
print(marks)
marks.reverse()
print(marks)
sorted gave a new list [91, 78, 65] and marks stayed [65, 91, 78]. Then sort() changed marks to [65, 78, 91], and reverse() flipped it.

Slicing: taking a part of a list

python
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
print(days[1:3])
print(days[:2])
print(days[-2:])
print(days[::-1])
A slice [start:stop] gives a NEW list from start up to, but not including, stop. The rules are the same as for slicing strings.

The alias mistake: b = a does not copy

Think of it like this: Writing b = a is like giving a friend a second key to your house. There is still only one house. If your friend moves the sofa, you find it moved too. a.copy() is like building a second house with the same furniture: a change in one house does not touch the other.
python
a = [1, 2, 3]
b = a
b.append(4)
print(a)

c = a.copy()
c.append(5)
print(a)
print(c)
b = a makes a second name for the same list, so a also shows the 4. c is a real copy, so adding 5 to c does not change a.

A list of lists: a marks table

python
table = [
    ["Asha", 78, 85],
    ["Ravi", 92, 70],
]
print(table[1][0])
for row in table:
    print(row[0], "total", row[1] + row[2])
table[1][0] means row 1, item 0: Ravi. Each row is itself a list. Shows Asha total 163 and Ravi total 162.
Tip: Never write marks = marks.sort(). sort() returns None, so marks becomes None and your list is lost. Write marks.sort() on its own line, or write ranked = sorted(marks).

Watch the lesson

List methods and slicing · 1/7

List methods and slicing

In this lesson you will learn the methods that change a list, and how to take a slice of a list.

Prefer a video by a teacher? Find free videos on “python list methods append sort slicing tutorial” on YouTube ↗

In real life: A kirana shop's shopping list

Sunita keeps the list of things to buy from the wholesale market on her phone. During the day she adds items, removes what a neighbour already gave her, and at night she sorts the list so it is easy to read at the market. A copy of the list goes to her son, and his changes must not spoil hers.

python
to_buy = ["rice", "oil"]
to_buy.append("sugar")
to_buy.extend(["dal", "tea"])
to_buy.remove("oil")
to_buy.sort()
print(to_buy)
son_list = to_buy.copy()
son_list.append("biscuits")
print(len(to_buy), len(son_list))
Shows ['dal', 'rice', 'sugar', 'tea'], then 4 5: the copy did not change Sunita's list.

Practice (0/3 done)

Task 1 · Code · Python

Write a function add_item(cart, item) that adds item to the END of the list cart and then returns cart.

Task 2 · Code · Python

Write a function top_three(marks) that returns a new list of the three highest marks, biggest first. Do not change the original list. Example: top_three([55, 90, 72, 88, 61]) returns [90, 88, 72].

Task 3 · Code · Python

A marks table is a list of rows, and each row is a list of one student's marks. Write a function student_totals(table) that returns a list with the total of each row. Example: student_totals([[80, 75, 90], [60, 70, 65]]) returns [245, 195].

Quick quiz

Question 1

1.After x = [1, 2] and x.append([3, 4]), what is len(x)?

Question 2

2.What does [10, 20, 30, 40][1:3] give?

Question 3

3.After a = [1, 2], b = a and b.append(3), what is a?

Question 4

4.What does marks.sort() return?

Question 5

5.items = ["a", "b", "c"]. What does items.pop() give?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: Lists: many values in one name