List Methods

Lists are objects and thus have methods. Table 11, List Methods gives some of the most commonly used list methods.


Table 11. List Methods

Method

Description

L.append(v)

Appends value v to list L.

L.clear()

Removes all items from list L.

L.count(v)

Returns the number of occurrences of v in list L.

L.extend(v)

Appends the items in v to L.

L.index(v)

Returns the index of the first occurrence of v in L—an error is raised if v doesn’t occur in L.

L.index(v, beg)

Returns the index of the first occurrence of v at or after index beg in L—an error is raised if v doesn’t occur in that part of L.

L.index(v, beg, end)

Returns the index of the first occurrence of v between indices beg (inclusive) and end (exclusive) in L; an error is raised if v doesn’t occur in that part of L.

L.insert(i, v)

Inserts value v at index i in list L, shifting subsequent items to make room.

L.pop()

Removes and returns the last item of L (which must be nonempty).

L.remove(v)

Removes the first occurrence of value v from list L.

L.reverse()

Reverses the order of the values in list L.

L.sort()

Sorts the values in list L in ascending order (for strings with the same letter case, it sorts in alphabetical order).

L.sort(reverse=True)

Sorts the values in list L in descending order (for strings with the same letter case, it sorts in reverse alphabetical order).


Here is a sample interaction showing how we can use list methods to construct a list of many colors:

 >>>​​ ​​colors​​ ​​=​​ ​​[​​'red'​​,​​ ​​'orange'​​,​​ ​​'green'​​]
 >>>​​ ​​colors.extend([​​'black'​​,​​ ​​'blue'​​])
 >>>​​ ​​colors
 ['red', 'orange', 'green', 'black', 'blue']
 >>>​​ ​​colors.append(​​'purple'​​)
 >>>​​ ​​colors
 ['red', 'orange', 'green', 'black', 'blue', 'purple']
 >>>​​ ​​colors.insert(2,​​ ​​'yellow'​​)
 >>>​​ ​​colors
 ['red', 'orange', 'yellow', 'green', 'black', 'blue', 'purple']
 >>>​​ ​​colors.remove(​​'black'​​)
 >>>​​ ​​colors
 ['red', 'orange', 'yellow', 'green', 'blue', 'purple']

All the methods shown here modify the list instead of creating a new list. The same is true for the methods clear, reverse, sort, and pop. Of those methods, only pop returns a value other than None. (pop returns the item that was removed from the list.) In fact, the only method that returns a list is copy, which is equivalent to L[:].

Finally, a call to append isn’t the same as using +. First, append appends a single value, while + expects two lists as operands. Second, append modifies the list rather than creating a new one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.254.61