Learn · Run · Break · Fix
A learning series from A Wandering Mind
Eighteen interlinked lessons on strings, lists, files, exceptions, and dictionaries—with original explanations, runnable examples, real output, and supporting CPSC 1301K lectures.
>>> guide = { ... "lessons": 18, ... "modules": 5, ... "python": "3.10+" ... } >>> guide["goal"] = "understand it"
List Methods and Built-in Functions in Python
Python gives lists their own methods for changing, searching, and organizing their contents, while built-in functions such as len(), min(), max(), sum(), and sorted() work by accepting a list as an argument. The distinction matters because some operations mutate the original list, some simply report information, and some create a new value instead.
Methods belong to list objects
A method is called through an object using dot notation. If items is a list, an expression such as items.append("new") asks that list object to perform its append operation. The method name comes after the dot, and any information the method needs appears inside parentheses.
This is different from a built-in function such as len(items). There, the function name appears first and the list is passed into the function. Both forms are normal Python, but recognizing the difference helps you read documentation, understand return values, and predict whether the original list may change.
numbers = [10, 20]
numbers.append(30)
numbers.insert(1, 15)
numbers.extend([40, 50])
print(numbers)
[10, 15, 20, 30, 40, 50]
append() adds one object to the end of the list. insert(index, value) places one value at a specified position and shifts later elements to the right. extend(iterable) adds each element from another iterable to the end. That last distinction is important: appending [40, 50] would add one nested list element, while extending with [40, 50] adds the two numbers as separate elements.
Method names often describe intent. Use append() for one new item, insert() for one new item at a specific position, and extend() when another sequence should contribute each of its elements.
Some methods inspect instead of changing
Not every list method mutates the list. count(value) reports how many elements compare equal to a requested value. index(value) returns the position of the first matching value. Both inspect the existing list and return information without rearranging or deleting its contents.
pets = ["cat", "dog", "cat", "bird"]
print(pets.count("cat"))
print(pets.index("bird"))
2
3
The list contains two strings equal to "cat", so count() returns 2. The first "bird" is at index 3, so index() returns 3. If the requested value is absent, count() returns zero, while index() raises ValueError. That difference makes the choice of method meaningful.
sort() and sorted() solve similar problems differently
Ordering a list is one of the clearest places to see the difference between a mutating method and a built-in function. The list method sort() rearranges the existing list in place. The built-in function sorted() accepts an iterable and returns a new sorted list, leaving the original sequence unchanged.
scores = [88, 72, 95, 81]
ascending = sorted(scores)
print(scores)
print(ascending)
scores.sort(reverse=True)
print(scores)
[88, 72, 95, 81]
[72, 81, 88, 95]
[95, 88, 81, 72]
The first printed list proves that sorted(scores) did not modify scores. Instead, the result was stored in ascending. The later call to scores.sort(reverse=True) changes scores itself into descending order.
A common silent mistake is writing result = scores.sort() and expecting result to contain the sorted list. Methods such as sort() that primarily mutate an object return None. If you need a separate sorted list, use sorted(). If you want the existing list rearranged, call sort() and then keep using that list variable.
Built-in functions summarize numeric lists
Several built-ins become especially useful when list elements are numeric. You already used len() in Lesson 4. min() returns the smallest value, max() returns the largest, and sum() adds numeric elements together. These functions do not belong specifically to lists; they accept appropriate iterable values more generally.
temperatures = [72, 75, 68, 80]
print(len(temperatures))
print(min(temperatures))
print(max(temperatures))
print(sum(temperatures))
average = sum(temperatures) / len(temperatures)
print(f"{average:.1f}")
4
68
80
295
73.8
The built-ins provide the ingredients for a simple average without writing a loop: total the values with sum() and divide by the number of values from len(). This assumes the list is non-empty; otherwise the division step would divide by zero. Later lessons will give you more ways to process lists element by element.
items.append(x)Mutates the list by adding one object to the end.
items.extend(values)Adds each value from another iterable.
items.sort()Rearranges the existing list and returns None.
sorted(items)Creates a new sorted list and leaves the source unchanged.
Common mistakes with methods and built-ins
The following failures were executed in Python. They show why method signatures, missing values, and element types matter.
items = ["a", "b"]
items.append("c", "d")
Traceback (most recent call last):
File "/tmp/awm_lesson9/m1.py", line 2, in <module>
items.append("c", "d")
~~~~~~~~~~~~^^^^^^^^^^
TypeError: list.append() takes exactly one argument (2 given)
append() accepts one object. If you want to add two separate elements, call append() twice or use extend() with an iterable containing those two elements.
items = ["a", "b", "c"]
print(items.index("z"))
Traceback (most recent call last):
File "/tmp/awm_lesson9/m2.py", line 2, in <module>
print(items.index("z"))
~~~~~~~~~~~^^^^^
ValueError: 'z' is not in list
index() promises to return a position for a matching value. If there is no match, there is no valid position to return. Use a membership test such as if "z" in items: first when absence is an expected possibility.
values = [10, "20", 30]
print(sum(values))
Traceback (most recent call last):
File "/tmp/awm_lesson9/m3.py", line 2, in <module>
print(sum(values))
~~~^^^^^^^^
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The string "20" is not the integer 20. sum() combines values through numeric addition, so a stray string breaks the operation. Clean or convert the data before treating the collection as numeric.
values = [10, "20", 30]
values.sort()
Traceback (most recent call last):
File "/tmp/awm_lesson9/m4.py", line 2, in <module>
values.sort()
~~~~~~~~~~~^^
TypeError: '<' not supported between instances of 'str' and 'int'
Sorting requires Python to establish an order between elements. Integers can be compared with integers and strings with strings, but Python does not invent an ordering rule between an integer and a string. A mixed list may be legal to store, yet still be inappropriate for a particular function or method.
Supporting classroom explanations
This page is original A Wandering Mind instructional material. The two CPSC 1301K lectures below provide additional classroom reinforcement for commonly used list methods and the built-in functions that operate on lists.
What it adds: a broader classroom walkthrough of common methods available on list objects and how those methods affect list contents.
What it adds: a focused explanation of built-in functions that accept lists and return useful measurements, totals, or ordered results.
Try it yourself
Before opening the answers, decide whether each operation should change the original list or merely return information. That question is as important as memorizing the method name.
Exercise 1 · Append one, extend with two
Start with items = ["pen"]. Append "notebook", then extend the list with "eraser" and "ruler". Print the result.
Show one answer
items = ["pen"]
items.append("notebook")
items.extend(["eraser", "ruler"])
print(items)
['pen', 'notebook', 'eraser', 'ruler']
Exercise 2 · Count and locate
Create values = [4, 9, 2, 9, 7]. Print how many times 9 appears, then print the index of 7.
Show one answer
values = [4, 9, 2, 9, 7]
print(values.count(9))
print(values.index(7))
2
4
Exercise 3 · Sort without changing the source
Create prices = [12.5, 8.0, 15.5, 4.0]. Use sorted() to create an ordered copy, then print that copy and the formatted total of the original prices.
Show one answer
prices = [12.5, 8.0, 15.5, 4.0]
ordered = sorted(prices)
print(ordered)
print(f"Total: ${sum(prices):.2f}")
[4.0, 8.0, 12.5, 15.5]
Total: $40.00
What you should carry into Lesson 10
You now have a practical list toolbox and, more importantly, a way to classify its tools. Methods such as append(), insert(), extend(), and sort() operate through a list object and may mutate it. Methods such as count() and index() return information. Built-ins such as len(), min(), max(), sum(), and sorted() accept the collection as an argument and return a result.
The next lesson shifts from individual operations to repetition over data. Continue to Looping Over Lists and Nested Lists to process each element with a for loop and then extend the idea to lists that contain other lists.
