- 5.1 Introduction
- 5.2 Lists
- 5.3 Tuples
- 5.4 Unpacking Sequences
- 5.5 Sequence Slicing
- 5.6 del Statement
- 5.7 Passing Lists to Functions
- 5.8 Sorting Lists
- 5.9 Searching Sequences
- 5.10 Other List Methods
- 5.11 Simulating Stacks with Lists
- 5.12 List Comprehensions
- 5.13 Generator Expressions
- 5.14 Filter, Map and Reduce
- 5.15 Other Sequence Processing Functions
- 5.16 Two-Dimensional Lists
- 5.17 Intro to Data Science: Simulation and Static Visualizations
- 5.18 Wrap-Up
5.10 Other List Methods
Lists also have methods that add and remove elements. Consider the list color_names:
In [1]: color_names = ['orange', 'yellow', 'green']
Inserting an Element at a Specific List Index
Method insert adds a new item at a specified index. The following inserts 'red' at index 0:
In [2]: color_names.insert(0, 'red') In [3]: color_names Out[3]: ['red', 'orange', 'yellow', 'green']
Adding an Element to the End of a List
You can add a new item to the end of a list with method append:
In [4]: color_names.append('blue') In [5]: color_names Out[5]: ['red', 'orange', 'yellow', 'green', 'blue']
Adding All the Elements of a Sequence to the End of a List
Use list method extend to add all the elements of another sequence to the end of a list:
In [6]: color_names.extend(['indigo', 'violet']) In [7]: color_names Out[7]: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
This is the equivalent of using +=. The following code adds all the characters of a string then all the elements of a tuple to a list:
In [8]: sample_list = [] In [9]: s = 'abc' In [10]: sample_list.extend(s) In [11]: sample_list Out[11]: ['a', 'b', 'c'] In [12]: t = (1, 2, 3) In [13]: sample_list.extend(t) In [14]: sample_list Out[14]: ['a', 'b', 'c', 1, 2, 3]
Rather than creating a temporary variable, like t, to store a tuple before appending it to a list, you might want to pass a tuple directly to extend. In this case, the tuple’s parentheses are required, because extend expects one iterable argument:
In [15]: sample_list.extend((4, 5, 6)) # note the extra parentheses In [16]: sample_list Out[16]: ['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
A TypeError occurs if you omit the required parentheses.
Removing the First Occurrence of an Element in a List
Method remove deletes the first element with a specified value—a ValueError occurs if remove’s argument is not in the list:
In [17]: color_names.remove('green') In [18]: color_names Out[18]: ['red', 'orange', 'yellow', 'blue', 'indigo', 'violet']
Emptying a List
To delete all the elements in a list, call method clear:
In [19]: color_names.clear() In [20]: color_names Out[20]: []
This is the equivalent of the previously shown slice assignment
color_names[:] = []
Counting the Number of Occurrences of an Item
List method count searches for its argument and returns the number of times it is found:
In [21]: responses = [1, 2, 5, 4, 3, 5, 2, 1, 3, 3, ...: 1, 4, 3, 3, 3, 2, 3, 3, 2, 2] ...: In [22]: for i in range(1, 6): ...: print(f'{i} appears {responses.count(i)} times in responses') ...: 1 appears 3 times in responses 2 appears 5 times in responses 3 appears 8 times in responses 4 appears 2 times in responses 5 appears 2 times in responses
Reversing a List’s Elements
List method reverse reverses the contents of a list in place, rather than creating a reversed copy, as we did with a slice previously:
In [23]: color_names = ['red', 'orange', 'yellow', 'green', 'blue'] In [24]: color_names.reverse() In [25]: color_names Out[25]: ['blue', 'green', 'yellow', 'orange', 'red']
Copying a List
List method copy returns a new list containing a shallow copy of the original list:
In [26]: copied_list = color_names.copy() In [27]: copied_list Out[27]: ['blue', 'green', 'yellow', 'orange', 'red']
This is equivalent to the previously demonstrated slice operation:
copied_list = color_names[:]