The most popular list methods

The following are some of the most frequently used list methods:

• To add an item to the end of a list, use the append() method. This method changes the list in place. It returns None.

This example adds the string 'apple' to a list:

basket = ['apple', 'banana', 'orange'] basket.append('apple')

• To find out the number of times a value occurs in a list, use the count( value ) method.

This example counts the number of times the string 'apple' appears.

• To add to a list the contents of another sequence object or iterable (an object whose elements can be retrieved one at a time), use the extend() method. If the iterable is a string, each character is added individually.

This example adds each character of the string 'pear'.

>>> x = ['apple', 'apple', 'banana', 'orange'] >>> x.extend('pear') >>> x

['apple', 'apple', 'banana', 'orange', 'p', 'e', 'a', 'r']

• To delete the first occurrence of an item in a list, use the remove() method. It raises a valueError if the item isn't found.

This example removes the first 'apple' string.

The sort() and reverse() methods both change the list itself.

o The sort() method's default ordering is alphabetical for lists containing text, numerical for lists containing numbers, and so on. o The reverse() method inverts the positions of items in a list.

Tip Python 2.4 and later also support these built-in functions:

o sorted(), which returns a sorted copy of the list (or other iterable).

o reversed(), which returns an iterator object that lets you use a loop to process the items in the list in reverse order.

The following examples show the use of the sort() and reverse() methods on a list of strings:

['a', 'apple', 'banana', 'e', 'orange', 'p', 'r'] >>> x.reverse() >>> x

Was this article helpful?

0 0

Post a comment