List methods in python

In this article we are going to see about the various methods of the list data type. The 9 methods that we are going to see in this article are,

  1. append
  2. extend
  3. insert
  4. pop
  5. remove
  6. index
  7. count
  8. sort
  9. reverse

Append

The append() methods adds a new element at the end of the list. The following code snippet explains this clearly.

list append method

Adding a new colour to the list adds it to the end.

Extend

The extend methods takes a list and adds it to another list combining them to a single list.

list extend method

The extend methods add the elements of the second list to the first list combining them to a single list.

Insert

The insert method takes two arguments. The item to be added to the list and the position at which it has to be added. This is more suitable to use than append when we want to insert the element in a particular position.

list insert method

This code snippet inserts value “2” at position “1”. Of course the index begins from 0.

remove

The remove() method takes an element as input and removes if that element is present in the list otherwise it will return error if there is no such item in the list.

python list remove method

pop

The pop method takes an index as argument and removes element from that index. If no index is given it will remove the last element from the list.

list pop method

Here i have given the index value as 2, so the number at the index 2 which is 9 is removed.

pop method without parameters

In this code snippet no index is given in the pop method, so it pops the last element and returns it.

index

The index method takes an element as argument and returns the index of that element in the list.

index method python

In this code snippet i have given the value 9 as the argument and its index is returned which is 2.

count

The count method counts the number of times a particular element is present in the list. It takes the element as the argument.

count method python

Since the number 4 is present 3 times in the list, the count method returns 3.

sort

The sort method can be used to sort the dictionary either in ascending or descending order.

python list sort method

reverse

The reverse method reverses the entire list. This is similar to list[::-1]

python list reverse method

We can also reverse the list by simply doing [::-1] to the list. This will work for the strings as well.

Hope this was helpful.

Happy coding !

Leave a Reply

Your email address will not be published. Required fields are marked *