You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: concepts/list-methods/about.md
+53-28Lines changed: 53 additions & 28 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,16 +1,20 @@
1
1
# About
2
2
3
-
A [`list`][list] is a mutable collection of items in _sequence_. Like most collections (_see the built-ins [`tuple`][tuple], [`dict`][dict] and [`set`][set]_), lists can hold references to any (or multiple) data type(s) - including other lists. They can be copied in whole or in part via [slice notation][slice notation]. Like any [sequence][sequence type], elements within `lists` are referenced by `0-based index` number.
3
+
A [`list`][list] is a mutable collection of items in _sequence_. Like most collections (_see the built-ins [`tuple`][tuple], [`dict`][dict] and [`set`][set]_), lists can hold references to any (or multiple) data type(s) - including other lists.
4
+
They're considered a [sequence][sequence type] in Python, and can be copied in whole or in part via [slice notation][slice notation].
5
+
Like any sequence, elements within `lists` can be referenced by `0-based index` number from the left, or `-1-based index` number from the right.
4
6
5
-
Lists support both [common][common sequence operations] and [mutable][mutable sequence operations] sequence opterations like `min(<list>)`/`max(<list>)`, `<list>.index()`, `<list>.append()` and `<list>.reverse()`. Items can be iterated over using the `for item in <list>` construct, and `for item in enumerate(<list>)` can be used when both the element and index are needed.
7
+
Lists support both [common][common sequence operations] and [mutable][mutable sequence operations] sequence opterations like `min(<list>)`/`max(<list>)`, `<list>.index()`, `<list>.append()` and `<list>.reverse()`.
8
+
Items can be iterated over using the `for item in <list>` construct, and `for item in enumerate(<list>)` can be used when both the element and element index are needed.
6
9
7
-
Python provides many useful [methods][list-methods] for working with lists. Let's take a look at some of them.
10
+
Python provides many useful [methods][list-methods] for working with lists.
8
11
9
-
Keep in mind that when you manipulate a list with a list-method, **you alter the list** object that has been passed into the method. If you do not wish to mutate your original `list`, you will need to at least make a `shallow copy` of it via slice or `<list>.copy()`.
12
+
Becasue `lists` are mutable, list-methods **alter the original list object** passed into the method.
13
+
If mutation is undesirable, the original `list` needs to at least be copied via `shallow copy` via `slice` or `<list>.copy()`.
10
14
11
15
## Adding Items
12
16
13
-
If you want to add an item to the end of an existing list, use `list.append()`:
17
+
Adding items to the end of an existing list can be done via `<list>.append(<item>)`:
14
18
15
19
```python
16
20
>>> numbers = [1, 2, 3]
@@ -19,26 +23,26 @@ If you want to add an item to the end of an existing list, use `list.append()`:
19
23
[1, 2, 3, 9]
20
24
```
21
25
22
-
Rather than _appending_, `list.insert()` gives you the ability to add the item to a _specific index_ in the list.
26
+
Rather than _appending_, `<list>.insert(<index>, <item>)` adds the item to a _specific index_ within the list.
27
+
`<index>` is the index of the item _before which_ you want the new item to appear.
28
+
`<item>` is the element to be inserted.
23
29
24
-
`list.insert()` takes 2 parameters:
25
-
26
-
1. the index of the item _before which_ you want the new item to appear
27
-
2. the item to be inserted
28
-
29
-
**Note**: If the given index is 0, the item will be added to the start of the list. If the supplied index is greater than the last index on the list, the item will be added in the final position -- the equivalent of using `list.append()`.
30
+
**Note**: If `<index>` is 0, the item will be added to the start of the list.
31
+
If `<index>` is greater than the final index on the list, the item will be added in the final position -- the equivalent of using `<list>.append(<item>)`.
30
32
31
33
```python
32
34
>>> numbers = [1, 2, 3]
33
35
>>> numbers.insert(0, -2)
34
36
>>> numbers
35
37
[-2, 1, 2, 3]
38
+
36
39
>>> numbers.insert(1, 0)
37
40
>>> numbers
38
41
[-2, 0, 1, 2, 3]
39
42
```
40
43
41
-
If you have an iterable that you would like to _combine_ with your current list (concatenating the two), `list.extend()` can be used. `list.extend()` will _unpack_ the supplied iterable, adding its elements in the same order to the end of your list (_using `.append()` in this circumstance would add the entire iterable as a **single item**._).
44
+
An `iterable` can be _combined_ with an existing list (concatenating the two) via `<list>.extend(<iterable>)`.
45
+
`<list>.extend(<iterable>)` will _unpack_ the supplied iterable, adding its elements in the same order to the end of the target list (_using `<list>.append(<item>)` in this circumstance would add the entire iterable as a **single item**._).
42
46
43
47
```python
44
48
>>> numbers = [1, 2, 3]
@@ -57,22 +61,25 @@ If you have an iterable that you would like to _combine_ with your current list
57
61
58
62
## Removing Items
59
63
60
-
To delete an item from a list use `list.remove()`, passing the item to be removed as an argument. `list.remove()` will throw a `ValueError` if the item is not present in the list.
64
+
`<list>.remove(<item>)` can be used to remove an element from the list.
65
+
`<list>.remove(<item>)` will throw a `ValueError` if the element is not present in the list.
61
66
62
67
```python
63
68
>>> numbers = [1, 2, 3]
64
69
>>> numbers.remove(2)
65
70
>>> numbers
66
71
[1, 3]
67
72
68
-
# Trying to remove a value that is not in the list throws a ValueError
73
+
# Trying to remove a value that is not in the list throws a ValueError.
69
74
>>> numbers.remove(0)
70
75
ValueError: list.remove(x): x notinlist
71
76
```
72
77
73
-
Alternatively, using the `list.pop()` method will both remove **and**`return` an element for use.
78
+
Alternatively, using `<list>.pop(<item>)` method will both remove **and**`return` an element for use.
74
79
75
-
`list.pop()` takes one optional parameter: the index of the item you need to remove and receive. If the optional index argument is not specified, the last element of the list will be removed and returned to you. If you specify an index number higher than the length of the list, you will get an `IndexError`.
80
+
`<list>.pop(<item>)` takes one optional parameter: the `index` of the element to remove and return.
81
+
If the optional `<index>` argument is not specified, the last element of the list will be removed and returned.
82
+
If `<index>` is a higher number than the final index of the list, an `IndexError` will be thrown.
76
83
77
84
```python
78
85
>>> numbers = [1, 2, 3]
@@ -82,15 +89,18 @@ Alternatively, using the `list.pop()` method will both remove **and** `return` a
82
89
[2, 3]
83
90
>>> numbers.pop()
84
91
3
92
+
85
93
>>> numbers
86
94
[2]
95
+
96
+
# This will throw an error because there is only index 0.
87
97
>>> numbers.pop(1)
88
98
Traceback (most recent call last):
89
99
File "<stdin>", line 1, in<module>
90
100
IndexError: pop index out of range
91
101
```
92
102
93
-
If you want to remove all items from a `list`, use `list.clear()`. It does not take any parameters.
103
+
All items can be removed from a `list` via `<list>.clear()`. It does not take any parameters.
94
104
95
105
```python
96
106
>>> numbers = [1, 2, 3]
@@ -103,7 +113,7 @@ If you want to remove all items from a `list`, use `list.clear()`. It does not t
103
113
104
114
## Reversing and reordering
105
115
106
-
You can reverse the order of list elements _***in place**_ with `<list>.reverse()`. This will mutate the original list.
116
+
The order of list elements can be reversed _**in place**_ with `<list>.reverse()`. This will mutate the original list.
107
117
108
118
```python
109
119
>>> numbers = [1, 2, 3]
@@ -112,7 +122,10 @@ You can reverse the order of list elements _***in place**_ with `<list>.reverse(
112
122
[3, 2, 1]
113
123
```
114
124
115
-
List elements can also be sorted _**in place**_ using `list.sort()`. Internally, Python uses [`Timsort`][timsort] to arrange elements. The default order is _ascending_. Take a look at the Python docs for some [additional tips and techniques for sorting][sorting how to] lists effectively.
125
+
List elements can be sorted _**in place**_ using `<list>.sort()`.
126
+
Internally, Python uses [`Timsort`][timsort] to arrange the elements.
127
+
The default order is _ascending_.
128
+
The Python docs have [additional tips and techniques for sorting][sorting how to]`lists` effectively.
116
129
117
130
```python
118
131
>>> names = ["Tony", "Natasha", "Thor", "Bruce"]
@@ -123,7 +136,7 @@ List elements can also be sorted _**in place**_ using `list.sort()`. Internally
123
136
["Bruce", "Natasha", "Thor", "Tony"]
124
137
```
125
138
126
-
If you want to sort a list in _descending_ order, pass a `reverse=True` argument:
139
+
To sort a list in _descending_ order, pass a `reverse=True` argument to the method:
127
140
128
141
```python
129
142
>>> names = ["Tony", "Natasha", "Thor", "Bruce"]
@@ -132,13 +145,17 @@ If you want to sort a list in _descending_ order, pass a `reverse=True` argument
132
145
["Tony", "Thor", "Natasha", "Bruce"]
133
146
```
134
147
135
-
For cases where mutating the original list is undesirable, the built-in functions [`sorted()`][sorted] and [`reversed()`][reversed] can be used. `sorted(<list>)` will return a sorted _copy_, and takes the same parameters as `<list>.sort()`. `reversed(<list>)` returns an _iterator_ that yields the list's items in reverse order. We'll talk about iterators more in later exercises.
148
+
For cases where mutating the original `list` is undesirable, the built-in functions [`sorted()`][sorted] and [`reversed()`][reversed] can be used.
149
+
`sorted(<list>)` will return a sorted _copy_, and takes the same parameters as `<list>.sort()`.
150
+
`reversed(<list>)` returns an _iterator_ that yields the list's items in reverse order.
151
+
`Iterators` will be covered in detail in another exercise.
136
152
137
153
<br>
138
154
139
155
## Occurrences of an item in a list
140
156
141
-
You can find the number of occurrences of an element in a list with the help of `list.count()`. It takes the item you need to tally as its argument and returns the total number of times it appears on the list.
157
+
Finding the number of occurrences of an element in a list can be done with the help of `<list>.count(<item>)`.
158
+
It returns the total number of times `<item>` appears as an element in the list.
142
159
143
160
```python
144
161
>>> items = [1, 4, 7, 8, 2, 9, 2, 1, 1, 0, 4, 3]
@@ -150,9 +167,9 @@ You can find the number of occurrences of an element in a list with the help of
150
167
151
168
## Finding the index of items
152
169
153
-
`list.index()` will return the index number of the _first occurrence_ of an item passed in. If there are no occurrences, a `ValueError` is raised. If you don't need the exact position of an item and are only checking that it is present inside the list, the built-in `in` operator is more efficient.
154
-
155
-
Indexing is zero-based, meaning the position of the first item is `0`.
170
+
`<list>.index(<item>)` will return the index number of the _first occurrence_ of an item passed in.
171
+
If there are no occurrences, a `ValueError` is raised.
172
+
Indexing is 0-based from the left, meaning the position of the first item is index`0`.
156
173
157
174
```python
158
175
>>> items = [7, 4, 1, 0, 2, 5]
@@ -162,7 +179,7 @@ Indexing is zero-based, meaning the position of the first item is `0`.
162
179
ValueError: 10isnotinlist
163
180
```
164
181
165
-
You can also provide `start` and `end` indices to search within a specific section of the list:
182
+
Providing `start` and `end` indices will search within a specific section of the list:
@@ -180,7 +205,7 @@ Remember that variables in Python are labels that point to underlying objects an
180
205
181
206
Assigning a `list` object to a new variable _name_ does not copy the object or any of its referenced data. Any change made to the items in the `list` using the new variable name will also _impact the original_.
182
207
183
-
`<list>.copy()` will create a new `list` object, but **will not** create new objects for the referenced list _elements_. This is called a `shallow copy`. A `shallow copy` is usually enough when you want to add or remove items from one of the `list` objects without modifying the other. But if there is any chance that the _underlying_ elements of a `list` might be accidentally mutated (_thereby mutating all related shallow copies_),[`copy.deepcopy()`][deepcopy] in the `copy` module should be used to create a complete or "deep" copy of **all** references and objects.
208
+
`<list>.copy()` will create a new `list` object, but **will not** create new objects for the referenced list _elements_. This is called a `shallow copy`. A `shallow copy` is usually enough when you want to add or remove items from one of the `list` objects without modifying the other. But if there is any chance that the _underlying_ elements of a `list` might be accidentally mutated (_thereby mutating all related shallow copies_), [`copy.deepcopy()`][deepcopy] in the `copy` module should be used to create a complete or "deep" copy of **all** references and objects.
184
209
185
210
For a detailed explanation of names, values, list, and nested list behavior, take a look at this excellent blog post from [Ned Batchelder][ned batchelder] -- [Names and values: making a game board][names and values].
Copy file name to clipboardExpand all lines: concepts/list-methods/introduction.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
1
# Introduction
2
2
3
-
A [list][list] is a mutable collection of items in _sequence_. They're an extremely flexible and useful data structure that many built-in methods and operations in Python produce as output. Lists can hold reference to any (or multiple) data type(s) - including other lists or data structures such as [tuples][tuples], [sets][sets], or [dicts][dicts]. Python provides many useful and convenient [list methods][list-methods] for working with lists.
3
+
A [list][list] is a mutable collection of items in _sequence_. They're an extremely flexible and useful data structure that many built-in methods and operations in Python produce as output. Lists can hold reference to any (or multiple) data type(s) - including other `lists` or data structures such as [tuples][tuples], [sets][sets], or [dicts][dicts]. Python provides many useful and convenient [methods][list-methods] for working with lists.
0 commit comments