L

learnasyoulike

time


Python List Methods


Table of contents:

Python List: Methods


Python lists have several methods to add, remove, insert, sort items. Before exploring these methods, you may have a go through the python lists page to know the basics of python lists. Here is a summarized table containing the methods of list objects clicking which will take you to the respective details.

Python list methods


Except the last three, all of the above methods modify the given list.

Method list.append() - Add an item

The .append(item) method adds an item at the end of a list.

colors.append("blue") object method append what

An item may be from an integer object to list, tuple, set, dictionary, string, any object. But it must be a single item.

In the following we shall be appending such objects one by one. Observe the growth of the list in this process.

Append a list to a list

Remember that the list [5, 7] is a single element of variable odds, and can be accessed with odds[2]. Length of odds is 3 now.

odds[2][0] points to the first element of odds[2], and odds[2][1] points to the second element of odds[2].


Append a tuple to a list


The tuple (9, 11, 13) is a single element of variable odds, and can be accessed with odds[3]. Now, length of odds is 4.


Append a set to a list

The set {17, 15} is a single element of variable odds, and can be accessed with odds[4]. Now, length of odds is 5.

Note: How the set {15, 17} becomes {17, 15} ? This is an internal mechanism of python; we must remember that sets are unordered.



Append a dictionary to a list

The dictionary {19: 's', 21: 'u'} is a single element of variable odds, and can be accessed with odds[5]. Now, length of odds is 6.

Method list.insert() - Insert an item

A new item is inserted with the method .insert(index, item) at the given index.

In colors.insert(2, "yellow"), the new item "yellow" will have an index 2.

colors.insert(2, "yellow") object method insert where insert what

Like .append() method, .insert() also can insert list, tuple, set, dictionary, string or any object at the specified index.

Method list.pop() - Remove an item

The .pop(index) method removes an item at the index given. Note that .append() and .insert() does not return any immediate output; but .pop() displays the item that has been removed.


colors.pop(1) object method index of item to remove

If no index is passed, the last item is removed. If the given index is out of range, python raises an IndexError.

Method list.remove() - Remove an item

There is also the .remove(item) method, through which we can remove an item from a list.


animals.remove("cat") object method remove what

If the item is present more than once, only the first item is removed. If the given item is not found in the list, python raises a ValueError.

Method list.clear() - Remove all items

We use the .clear() method to remove all items from a list.

Method list.reverse() - Reverse the order of items

The .reverse() method reverses the current order of items of a list.

Method list.sort() - Sort items

The .sort() method sorts the items of a list in ascending or descending order.


Sort items in ascending order

Sort items in descending order

The .sort() method can also sort the items of a list in descending order if an argument reverse=True is passed to the method.

Method list.extend() - Join list and iterable

The .extend(iterable) method expands a list by appending all the items of an iterable. An iterable may be a list, tuple, set, dictionary or a string.

Extend a list with list items

Note that if we append a list with the .append() method, the whole list is added as a single element. But the .extend(iterable) method appends all the items of an iterable. An iterable may be a list, tuple, set, dictionary or a string.



Extend a list with tuple elements

A list can also be extended with the items of a tuple since the latter is iterable.



Extend a list with set members

Lists can also be extended with the items of a set since the latter is iterable.



Extend a list with dictionary keys

We can extend a list with the keys of a dictionary since dictionaries are also iterables.



Extend a list with characters of a string

A list can be extended with the characters of a string. Strings are iterables too.

Method list.copy() - Copy a list

The .copy() method creates a copy of the given list. The output of this method can be assigned to a variable.


The output variable will have a different identity.


Note: We can easily assign a list variable to a new variable. Our purpose will be satisfied.



Then why we need a separate .copy() ?
In the above, n is not exactly a copy of m, rather n is m. This means both n and m point to the same object.

You will find such identity comparison and the use of is operator in this page.


But in such assignments, if we modify one list, the other list will also be modified.

We changed the 2nd item of list m, but that change is also reflected in list n.
Check the output of id(m) and id(n), you will find both of them are to be the same.

Using .copy() creates different identities for the original and the copied lists.

Now list n is a separate object than list m. Their identities are different; and modifying one list will not be reflected in the other list.

We can also copy a list by slicing which we shall find in list slicing page.

Method list.count() - Count number of occurance of an item

The .count(item) method counts the number of occurance of a given item in a list.

In the above list, the item "red" is found two times; so 2 is returned as output. Item "gold" is not found, so 0 is the output.

Method list.index() - Find index of an item

The .index(item) method returns the index of the given item in a list.

If the given item is present more than once, index of the first item is returned. If the given item is not found in the list, a ValueError is raised by python.




--- x ---









Want to leave a message for me?