Home > Articles

This chapter is from the book

This chapter is from the book

5.10 Other List Methods

Lists also have methods that add and remove elements. Consider the list color_names:

In [1]: color_names = ['orange', 'yellow', 'green']

Inserting an Element at a Specific List Index

Method insert adds a new item at a specified index. The following inserts 'red' at index 0:

In [2]: color_names.insert(0, 'red')

In [3]: color_names
Out[3]: ['red', 'orange', 'yellow', 'green']

Adding an Element to the End of a List

You can add a new item to the end of a list with method append:

In [4]: color_names.append('blue')

In [5]: color_names
Out[5]: ['red', 'orange', 'yellow', 'green', 'blue']

Adding All the Elements of a Sequence to the End of a List

Use list method extend to add all the elements of another sequence to the end of a list:

In [6]: color_names.extend(['indigo', 'violet'])

In [7]: color_names
Out[7]: ['red', 'orange', 'yellow', 'green', 'blue',   'indigo', 'violet']

This is the equivalent of using +=. The following code adds all the characters of a string then all the elements of a tuple to a list:

In [8]: sample_list = []

In [9]: s = 'abc'

In [10]: sample_list.extend(s)

In [11]: sample_list
Out[11]: ['a', 'b', 'c']

In [12]: t = (1, 2, 3)

In [13]: sample_list.extend(t)

In [14]: sample_list
Out[14]: ['a', 'b', 'c', 1, 2, 3]

Rather than creating a temporary variable, like t, to store a tuple before appending it to a list, you might want to pass a tuple directly to extend. In this case, the tuple’s parentheses are required, because extend expects one iterable argument:

In [15]: sample_list.extend((4,   5, 6))  # note the extra parentheses

In [16]: sample_list
Out[16]: ['a', 'b', 'c', 1, 2, 3, 4, 5, 6]

A TypeError occurs if you omit the required parentheses.

Removing the First Occurrence of an Element in a List

Method remove deletes the first element with a specified value—a ValueError occurs if remove’s argument is not in the list:

In [17]: color_names.remove('green')

In [18]: color_names
Out[18]: ['red', 'orange', 'yellow', 'blue', 'indigo',   'violet']

Emptying a List

To delete all the elements in a list, call method clear:

In [19]: color_names.clear()

In [20]: color_names
Out[20]: []

This is the equivalent of the previously shown slice assignment

color_names[:] = []

Counting the Number of Occurrences of an Item

List method count searches for its argument and returns the number of times it is found:

In [21]: responses = [1, 2, 5, 4, 3, 5, 2, 1, 3, 3,
    ...:              1, 4, 3, 3, 3, 2, 3, 3, 2, 2]
    ...:

In [22]: for i in range(1, 6):
   ...:     print(f'{i} appears {responses.count(i)} times   in responses')
   ...:    
1 appears 3 times in responses
2 appears 5 times in responses
3 appears 8 times in responses
4 appears 2 times in responses
5 appears 2 times in responses

Reversing a List’s Elements

List method reverse reverses the contents of a list in place, rather than creating a reversed copy, as we did with a slice previously:

In [23]: color_names = ['red', 'orange', 'yellow', 'green', 'blue']

In [24]: color_names.reverse()

In [25]: color_names
Out[25]: ['blue', 'green', 'yellow', 'orange', 'red']

Copying a List

List method copy returns a new list containing a shallow copy of the original list:

In [26]: copied_list = color_names.copy()

In [27]: copied_list
Out[27]: ['blue', 'green', 'yellow', 'orange', 'red']

This is equivalent to the previously demonstrated slice operation:

        copied_list = color_names[:]

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.