Informatics Practices · Ch 4 — Working with Lists and Dictionaries
List Methods and Built-in Functions
List Methods and Built-in Functions
Lists come with a rich set of ready-made tools: methods that belong to the list type itself (called as list1.append(...), list1.sort(), and so on) and built-in functions that take a list as an argument (such as len(), min(), max(), sum(), sorted()). Knowing what each one does — and, just as importantly, whether it changes the original list or leaves it untouched — is essential for writing list-handling programs.
The table below summarises the tools covered here; detailed behaviour and examples follow.
| Method / Function | What it does |
|---|---|
len() | Returns the number of elements in the list |
list() | Creates an empty list, or builds a list from a sequence |
append() | Adds a single element at the end of the list |
extend() | Adds each element of another list at the end |
insert() | Inserts an element at a given index |
count() | Counts how many times an element appears |
index() | Returns the index of the first occurrence of an element |
remove() | Deletes the first occurrence of a given value |
pop() | Returns and deletes the element at a given index (last, if none given) |
reverse() | Reverses the order of elements in place |
sort() | Sorts the list in place |
sorted() | Returns a new sorted list, original unchanged |
min(), max(), sum() | Smallest element, largest element, total of elements |
Finding the size — len()
len() takes the list as its argument and returns its length, the total number of elements:
>>> list1 = [10, 20, 30, 40, 50]
>>> len(list1)
5
Creating lists — list()
Called with no argument, list() creates an empty list. Called with a sequence as the argument, it builds a list out of that sequence's items — passing a string, for instance, produces a list of its individual characters:
>>> list1 = list()
>>> list1
[]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']
Growing a list — append(), extend(), insert()
append() attaches a single element at the end of the list. If you append a list, that whole list goes in as one element — a nested list — not as several separate elements:
>>> list1 = [10, 20, 30, 40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10, 20, 30, 40]
>>> list1.append([50, 60])
>>> list1
[10, 20, 30, 40, [50, 60]]
extend() is the tool for merging: it takes a list and adds each of its elements individually at the end of the given list:
>>> list1 = [10, 20, 30]
>>> list2 = [40, 50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
Confusing append() with extend() is a classic error. list1.append([50, 60]) leaves the list one element longer (that element being a list), while list1.extend([50, 60]) leaves it two elements longer.
insert() places an element at any chosen position rather than at the end. It takes two arguments — the index and the element — and the existing elements from that index onwards shift right:
>>> list1 = [10, 20, 30, 40, 50]
>>> list1.insert(2, 25) # 25 goes to index 2
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0, 100) # 100 goes to the front
>>> list1
[100, 10, 20, 25, 30, 40, 50]
Searching a list — count() and index()
count() returns how many times a given element occurs in the list; if the element is absent it simply returns 0:
>>> list1 = [10, 20, 30, 10, 40, 10]
>>> list1.count(10)
3
>>> list1.count(90)
0
index() returns the index of the first occurrence of an element. Unlike count(), it does not tolerate a missing element — if the element is not present, a ValueError is raised:
>>> list1 = [10, 20, 30, 20, 40, 10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list
Deleting elements — remove() and pop()
remove() deletes by value: it removes the given element from the list, and if the value occurs several times, only the first occurrence goes. Asking it to remove a value that is not in the list raises a ValueError:
>>> list1 = [10, 20, 30, 40, 50, 30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError: list.remove(x): x not in list
pop() deletes by position — and it also hands the deleted element back to you as its return value. With an index argument it removes the element at that index; with no argument it returns and removes the last element:
>>> list1 = [10, 20, 30, 40, 50, 60]
>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10, 20, 30, 40, 50, 60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
Choose by what you know: use remove() when you know the value to delete, pop() when you know the position (or want the last element) and also need the deleted value back.
Rearranging a list — reverse(), sort() and sorted()
reverse() flips the order of the elements in place — the last becomes first and the first becomes last. It works on numbers and strings alike, because it does not compare elements at all, it only reverses their positions:
>>> list1 = [34, 66, 12, 89, 28, 99]
>>> list1.reverse()
>>> list1
[99, 28, 89, 12, 66, 34]
>>> list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']
sort() arranges the elements of the list in order, in place — the original arrangement is lost. Strings sort alphabetically, numbers numerically. Passing reverse = True sorts in descending order:
>>> list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra'] …
| Method | Description | Example |
|---|---|---|
| len() | Returns the length of the list passed as the argument | >>> list1 = [10,20,30,40,50] >>> len(list1) 5 |
| list() | Creates an empty list if no argument is passed Creates a list if a sequence is passed as an argument | >>> list1 = list() >>> list1 [ ] >>> str1= 'aeiou' >>> list1 = list(str1) >>> list1 ['a', 'e', 'i', 'o', 'u'] |
| append() | Appends a single element passed as an argument at the end of the list A list can also be appended as an element to an existing list | >>> list1 = [10,20,30,40] >>> list1.append(50) >>> list1 [10, 20, 30, 40, 50] >>> list1 = [10,20,30,40] >>> list1.append([50,60]) >>> list1 [10, 20, 30, 40, [50, 60]] |
| extend() | Appends each element of the list passed as argument at the end of the given list | >>> list1 = [10,20,30] >>> list2 = [40,50] >>> list1.extend(list2) >>> list1 [10, 20, 30, 40, 50] |
| insert() | Inserts an element at a particular index in the list | >>> list1 = [10,20,30,40,50] #inserts element 25 at index value 2 >>> list1.insert(2,25) >>> list1 [10, 20, 25, 30, 40, 50] >>> list1.insert(0,100) >>> list1 [100, 10, 20, 25, 30, 40, 50] |
| count() | Returns the number of times a given element appears in the list | >>> list1 = [10,20,30,10,40,10] >>> list1.count(10) 3 >>> list1.count(90) 0 |
| find() | Returns index of the first occurrence of the element in the list. If the element is not present, ValueError is generated | >>> list1 = [10,20,30,20,40,10] >>> list1.index(20) 1 >>> list1.index(90) ValueError: 90 is not in list |
| remove() | Removes the given element from the list. If the element is present multiple times, only the first occurrence is removed. If the element is not present, then ValueError is generated | >>> list1 = [10,20,30,40,50,30] >>> list1.remove(30) >>> list1 [10, 20, 40, 50, 30] >>> list1.remove(90) ValueError:list.remove(x):x not in list |
| pop() | Returns the element whose index is passed as argument to this function and also removes it from the list. If no argument is given, then it returns and removes the last element of the list | >>> list1 = [10,20,30,40,50,60] >>> list1.pop(3) 40 >>> list1 [10, 20, 30, 50, 60] >>> list1 = [10,20,30,40,50,60] >>> list1.pop() 60 >>> list1 [10, 20, 30, 40, 50] |
| reverse() | Reverses the order of elements in the given list | >>> list1 = [34,66,12,89,28,99] >>> list1.reverse() >>> list1 [ 99, 28, 89, 12, 66, 34] >>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog'] >>> list1.reverse() >>> list1 ['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger'] |
| sort() | Sorts the elements of the given list in place | >>>list1 = ['Tiger','Zebra','Lion', 'Cat', 'Elephant' ,'Dog'] >>> list1.sort() >>> list1 ['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra'] >>> list1 = [34,66,12,89,28,99] >>> list1.sort(reverse = True) >>>list1 [99,89,66,34,28,12] |