List methods
Picture a checkout queue. People join it at the end, and someone with a small child goes to the front. The cashier serves the first person, and the last one suddenly leaves. The queue is the same queue all along; only who is in it changes.
A list in a program lives the same way: items go into a cart, people leave a queue. For this, a list has its own methods. They are called with a dot, like string methods. But string methods return a new string, while these methods change the list itself:
queue = ["Ann", "Bob"]
queue.append("Kim")
queue.insert(0, "Zoe")
print(queue) # ['Zoe', 'Ann', 'Bob', 'Kim']
first = queue.pop(0)
last = queue.pop()
print(first, last, queue) # Zoe Kim ['Ann', 'Bob']
queue.remove("Bob")
queue.extend(["Lee", "Max"])
print(queue) # ['Ann', 'Lee', 'Max']Let's see what happens to the queue:
- At first,
'Ann'and'Bob'stand in it. queue.append("Kim")puts'Kim'at the end.queue.insert(0, "Zoe")lets'Zoe'go to the front, to the place with index0.queue.pop(0)takes away the first person,'Zoe', and returns her: she ends up infirst.queue.pop()with no argument takes away the last person,'Kim'.queue.remove("Bob")removes'Bob', wherever he stands.queue.extend(["Lee", "Max"])puts two people at the end at once.
Five methods
Five methods change what a list holds:
append(x)addsxto the end of the list;extend(items)adds all the elements ofitemsto the end, like+=;insert(i, x)insertsxbefore the element at indexi;pop(i)removes the element at indexiand returns it, andpop()removes the last one;remove(x)removes the first element equal tox.
Two methods stop the program when there is nothing to remove:
popon an empty list stops it with anIndexError;removeof a value that is not in the list stops it with aValueError.
append and extend
Both methods add to the end, but they count what they add differently.
The append method
append always adds exactly one element. nums.append([3, 4]) puts the whole list [3, 4] at the end as one element, and nums grows by one. In the queue, that is one person carrying a bag, not two people.
The extend method
extend goes over its argument and adds each of its elements separately. After nums.extend([3, 4]), nums grows by two. The form nums += [3, 4] works the same way.
Sorting
Picture books on a shelf. You can rearrange them right on the shelf in alphabetical order. Or you can write the titles on a sheet and order them there, leaving the shelf as it was. Python has both ways:
nums = [3, 1, 2]
ordered = sorted(nums)
print(ordered, nums) # [1, 2, 3] [3, 1, 2]
nums.sort(reverse=True)
print(nums) # [3, 2, 1]Let's go through the example:
- The
sorted(nums)function builds a new sorted list[1, 2, 3], andnumsstays[3, 1, 2]. - The
nums.sort(reverse=True)method rearranges the elements ofnumsitself, this time in descending order.
The sort method sorts a list in place: it changes the list itself and returns None. The keyword argument reverse=True sorts in descending order—in both sort and sorted. Strings are sorted alphabetically, with capital letters before lowercase ones.
Interviewers like to ask this: "How does sort differ from sorted?" The answer:
sortis a list method: it rearranges the list itself and returnsNone;sortedis a function: it returns a new list and leaves the original alone.
Strings and lists
A string often has to be cut into parts or put together from parts. Strings have a pair of methods for this.
The split method
split cuts a string into a list of strings, like scissors cutting a ribbon. Without an argument it splits the text on spaces, and several spaces in a row count as one. With an argument it splits on the given string.
The join method
join does the reverse: the string it is called on goes between the elements of the list. It glues only strings: it does not accept a list of numbers and stops the program with a TypeError.
words = "red green blue".split()
print(words) # ['red', 'green', 'blue']
print("3,14,15".split(",")) # ['3', '14', '15']
print("-".join(words)) # red-green-blueCommon mistake
The result of sort was assigned back to the variable:
nums = [3, 1, 2]
nums = nums.sort() # ✗
print(nums[0])TypeError: 'NoneType' object is not subscriptablesort sorted the list and returned None, and the assignment bound nums to that None. The sorted list is lost, and you cannot take an index of None. Call nums.sort() on its own line, or write nums = sorted(nums).
Key points
append,extend,insert,popandremovechange the list itself.appendadds exactly one element, andextendadds each element of its argument.sortsorts in place and returnsNone, andsortedreturns a new list.splitcuts a string into a list of strings, andjoinglues a list of strings into one.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.