Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Monday, 31 October 2016

Python List Methods - append(), sort(), remove(), reverse(), etc.

Hello readers! This is the 9th article of our Python tutorial series 'Python on Terminal' and we will be learning about List Methods in Python in this tutorial. In the previous article on Python Lists - Python Lists Creation, Concatenation, Repetition, Indexing and Slicing, we studied how to create lists, how two lists can be merged and repeated and how indexing and slicing works for Python lists. In this article, we will be learning about various methods associated with Python lists along with examples.


In the last article on Python Lists, we have already seen that, like everything in Python, a list is also an object. It is an instance of the Python class named list. Thus, every list in Python is associated with a number of methods, which when called upon a list object (list_object_name.method_name()), do some processing on list object and returns another Python object (not necessarily a list type only).

So, what all methods can we call on a Python list object? You can get the answer by passing a Python list as an argument to Python built-in dir() function. Lets create a list then and check this.

>>> myList = ['One', 2, 'Three', 4.00]
>>> dir(myList)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Again, as we've seen earlier in case of Python strings, list are also associated with 'Magic Methods' (the ones starting with double underscores, e.g. __add__ method), those Python uses internally. Let us now learn some important list methods in detail.

1. append() Method :

This method appends (inserts at the end) an element (a Python object) to the Python list. To check this, we need to create a list and check how this method works.

>>> myList = ['One', 2, 'Three', 4.00]
>>> myList.append('Five')
>>> myList
['One', 2, 'Three', 4.0, 'Five']

>>> myList.append(3*2)
>>> myList
['One', 2, 'Three', 4.0, 'Five', 6]

>>> import math
>>> myNum = math.sqrt(49)
>>> myList.append(myNum)
>>> myList
['One', 2, 'Three', 4.0, 'Five', 6, 7.0]

Thus, every time we call append() method on myList list object, the element is inserted at the end of myList. By the way, we have just grown a list object myList, meaning that a list is mutable. Let us be some more curious and check what if we provide another list as an argument. Will it concatenate both the lists or appends another list to myList -

>>> myList = ['One', 2, 'Three', 4.0]
>>> myList.append(['Five', 3*2 ])
>>> myList
['One', 2, 'Three', 4.0, ['Five', 6]]
>>> myList[-1]
['Five', 6]

The later option - it will append. There is a method extend() which does the concatenation.

2. count() Method :

This method counts the number of occurrences of an element in the list which the method is called on. So, myList.count('Foo') will count how many times the string Foo has occurred in the list object myList.

>>> myList = ['One', 2, 'Three', 4.0, 'One', 'Five', 2, 'One', 4.0, 'ONE', 4]

# Case-sensitive
>>> myList.count('One')
3

# 'int' and 'float'
>>> myList.count(4)
3
>>> type(4)
<type 'int'>
>>> type(4.0)
<type 'float'>
>>> 4 == 4.0
True

3. extend() Method :

This method takes an iterable (always remember this) and appends each item to the list. Thus, if we call this method on myList with another list (which is an iterable) as an argument, all the elements will be appended to myList.

>>> myList = ['One', 2, 'Three', 4.0]

# List as an argument
>>> myList.extend(['Five', 3*2 ])
>>> myList
['One', 2, 'Three', 4.0, 'Five', 6]

# 'range()' function as an argument
>>> myList.extend(range(7, 10))
>>> myList
['One', 2, 'Three', 4.0, 'Five', 6, 7, 8, 9]

# String as an argument
>>> myList.extend('Ten')
>>> myList
['One', 2, 'Three', 4.0, 'Five', 6, 7, 8, 9, 'T', 'e', 'n']

Please observe the last case very carefully. We have provided a string 'Ten' to the extend() method, expecting that the string object 'Ten' will be appended to myList. But, extend() accepts iterables and a Python string being an iterable, all the characters are appended to myList one-by-one and we can see the result.

4. index() Method :

This method is similar to the string index() method. It accepts an element as an argument and returns the index of the first occurrence of the element in the list, if it is present in the list, otherwise it will give out an error.

>>> myList = ['One', 2, 'Three', 4.0, 'Five', 6, 7, 8, 9]

>>> myList.index('Five')
4

>>> myNum = 4
>>> myList.index(myNum)
3

>>> myList.index('Six')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'Six' is not in list

5. insert() Method :

The append() method will always add an element to the last position of the list, whereas insert() method accepts an extra argument denoting the 'offset' at which the element has to be inserted.

>>> myList = ['One', 2, 'Three', 4.0, 'Five']

# Insert 'Zero' at index '0'
>>> myList.insert(0, 'Zero')
>>> myList
['Zero', 'One', 2, 'Three', 4.0, 'Five']

# 'append' using 'insert()' method
>>> myList.insert(len(myList), 'The End')
>>> myList
['Zero', 'One', 2, 'Three', 4.0, 'Five', 'The End']

6. pop() Method :

This method when used without any argument, returns the last element in the list. It does accept an optional argument with which we can specify the offset of the list element to be returned. When the element is returned, it is also removed from the list.

>>> myList = ['One', 2, 'Three', 4.0, 'Five']

# 'pop()' without argument -> Last element is returned and list is modified
>>> myList.pop()
'Five'
>>> myList
['One', 2, 'Three', 4.0]

# Item at index '1' is returned and list is modified
>>> myList.pop(1)
2
>>> myList
['One', 'Three', 4.0]

# 'pop()' method on empty list gives out error
>>> [].pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop from empty list

7. remove() Method :

Using pop() method, we can remove an element from a list using it's offset, while with remove() method, we can remove an element from a list using it's value. pop() method with no argument removes last list element, but this won't work in case of remove() method. We must provide the value of the element that needs to be removed.

>>> myList = ['One', 2, 'Three', 4.0, 'Five']

# It takes exactly one argument !
>>> myList.remove()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)

>>> myList.remove(4)
>>> myList
['One', 2, 'Three', 'Five']

>>> myStr = 'Three'
>>> myList.remove(myStr)
>>> myList
['One', 2, 'Five']

8. reverse() Method :

This method when called on a list object, it reverses it in place, without returning anything. It means that, the contents of the original list are reversed and list is modified. In this context, let me also mention the built-in list reverse iterator object reversed, that returns a reversed list object, with the original list not getting modified.

>>> myList = ['One', 2, 'Three', 4.0, 'Five']

# 'reverse()' reverses the original list in-place
>>> myList.reverse()
>>> myList
['Five', 4.0, 'Three', 2, 'One']
>>> myList = ['One', 2, 'Three', 4.0, 'Five']

# With 'reversed()' original list is not modified
>>> list(reversed(myList))
['Five', 4.0, 'Three', 2, 'One']
>>> print reversed(myList)
<listreverseiterator object at 0x7ff2e1fdbe10>
>>> myList
['One', 2, 'Three', 4.0, 'Five']

9. sort() Method :

This method when called on a list object, orders the list elements in ascending order by default, original list is modified in-place. This method can take arguments so as to change the behavior of the default sorting process.

>>> myList = ['One', 2, 'Three', 4.0, 'Five']
>>> myList.sort()
>>> myList
[2, 4.0, 'Five', 'One', 'Three']

# Sort in descending order
>>> myList = ['One', 2, 'Three', 4.0, 'Five']
>>> myList.sort(reverse=True)
>>> myList
['Three', 'One', 'Five', 4.0, 2]

There is a Python built-in function sorted, which accepts a list type object as an argument and returns a sorted version of that list without modifying the original list. You can try that out - sorted(myList)

With this, we have learned all the important list methods along with some examples. Python lists are very powerful and useful data structures and you would use them most of the times. So, it is very essential to know all the methods associated with them, study their behaviors and use them accordingly. Thank you for stopping by and going through this article. Please do share your views and opinions in the comment section below and stay tuned for more articles.

This article is originally published at www.codeninja.in - Introduction to Python List Methods

0 comments:

Post a Comment