Working with Lists and Dictionaries
List methods and functions
Choose the right list method.
Functions and methods for lists:
- len(list1): number of elements.
- list(): makes an empty list, or a list from a sequence: list('aeiou') gives ['a', 'e', 'i', 'o', 'u'].
- append(x): adds one element at the end. If x is itself a list, it is added as a single (nested) element: [10, 20, 30, 40].append([50, 60]) gives [10, 20, 30, 40, [50, 60]].
- extend(list2): adds each element of list2 at the end: [10, 20, 30] extended with [40, 50] gives [10, 20, 30, 40, 50].
- insert(i, x): puts x at index i, shifting the rest right.
- count(x): how many times x appears.
- index(x): the index of the first x; a ValueError if x is absent. (The book's table calls this 'find()', but Python lists have no find() method; the method is index().)
- remove(x): deletes the first x only; a ValueError if absent.
- pop(i): removes and returns the element at index i; pop() with no argument removes and returns the last element.
- reverse(): reverses the list in place.
- sort(): sorts the list in place (ascending); sort(reverse = True) sorts descending.
- sorted(list1): returns a new sorted list and leaves list1 unchanged.
- min(), max(), sum(): smallest, largest and total of the elements.
Methods such as append(), extend(), insert(), remove(), pop(), reverse() and sort() change the list itself; len(), count(), index(), sorted(), min(), max() and sum() only read it.
Example (new): with fruits = ['mango', 'apple', 'banana'], fruits.insert(1, 'guava') gives ['mango', 'guava', 'apple', 'banana']; then fruits.remove('apple') leaves ['mango', 'guava', 'banana']; and sorted(fruits) returns ['banana', 'guava', 'mango'] while fruits itself stays in its old order.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.