diff --git a/native-datatypes.html b/native-datatypes.html index 5870256..971624f 100644 --- a/native-datatypes.html +++ b/native-datatypes.html @@ -334,6 +334,72 @@ ValueError: list.index(x): x not in list
index() method finds the first occurrence of a value in the list. In this case, 'new' occurs twice in the list, in a_list[2] and a_list[4], but the index() method will return only the index of the first occurrence.
-1). While this may seem annoying at first, I think you will come to appreciate it. It means your program will crash at the source of the problem instead of failing strangely and silently later.
+
+Lists can expand and contract automatically. You’ve seen the expansion part. There are several different ways to remove items from a list as well. + +
+>>> a_list = ['a', 'b', 'new', 'mpilgrim', 'new'] +>>> a_list[1] +'b' +>>> del a_list[1] ① +>>> a_list +['a', 'new', 'mpilgrim', 'new'] +>>> a_list[1] ② +'new'+
1 after deleting index 1 does not result in an error. All items after the deleted item shift their positional index to “fill the gap” created by deleting the item.
+Don’t know the positional index? Not a problem; you can remove items by value instead. + +
+>>> a_list.remove('new') ① +>>> a_list +['a', 'mpilgrim', 'new'] +>>> a_list.remove('new') ② +>>> a_list +['a', 'mpilgrim'] +>>> a_list.remove('new') +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +ValueError: list.remove(x): x not in list+
remove() method. The remove() method takes a value and removes the first occurrence of that value from the list. Again, all items after the deleted item will have their positional indices bumped down to “fill the gap.” Lists never have gaps.
+remove() method has often as you like, but it will raise an exception if you try to remove a value that isn’t in the list.
+Another interesting list method is pop(). The pop() method is yet another way to remove items from a list, but with a twist.
+
+
+>>> a_list = ['a', 'b', 'new', 'mpilgrim'] +>>> a_list.pop() ① +'mpilgrim' +>>> a_list +['a', 'b', 'new'] +>>> a_list.pop(1) ② +'b' +>>> a_list +['a', 'new'] +>>> a_list.pop() +'new' +>>> a_list.pop() +'a' +>>> a_list.pop() ③ +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +IndexError: pop from empty list+
pop() list method removes the last item in the list and returns the value it removed.
+pop() method. It will remove that item, shift all the items after it to “fill the gap,” and return the value it removed.
+pop() on an empty list raises an exception.
+
+
You can also use a list in a boolean context, such as an if statement.