List Methods
List Methods
● Here the value "violet" is actually inserted at index 5, even though .insert()
was called with 10 for the index.
● You can also use negative indices with .insert():
● This inserts "indigo" into the slot at index -1 which is the last element of the
list. The value "violet" is shifted to the right by one slot.
Note:
● When you .insert() an item into a list, you do not need to assign the result to
the original list.
● For example, the following code actually erases the colors list:
● .insert() is said to alter colors in place. This is true for all list methods that do
not return a value.
2.list.pop()
● The list.pop() method takes one parameter, an index i, and removes the value
from the list at that index. The value that is removed is returned by the
method:
● Python raises an IndexError if you pass to .pop() an argument larger than the
last index:
After calling .append(), the length of the list increases by one and the value
"indigo" is inserted into the final slot.
4. list.extend()
The list.extend() method is used to add several new elements to the end of a list:
The argument passed to .extend() is another list, but it could also be a tuple. For
example, the above example could be written as follows:
remove(<obj>)
● remove(<obj>) removes object <obj> from list a.
● If <obj> isn’t in a, an exception is raised:
Lists of Numbers: built-in functions
● Python has a couple of useful built-in functions for working with lists of
numbers.
● One very common operation with lists of numbers is to add up all the values
to get the total. You can do this with a for loop:
● The built-in sum() function takes a list as an argument and returns the total of
all the values in the list.
● Besides sum(), there are two other useful built-in functions for working with
lists of numbers: min() and max().