Python- List Manipulation

Posted by Anoop Nair on November 17, 2017 Tags: Python
To read about the basics of python list go to - Python Lists- The Basics

This will be small post I will go through most of the inbuilt methods of python for list manipulation then at the end I will show the examples.

List Methods

list.append(x) - This will append the element x to the end of the list.

list.insert(index,x) - Insert() method will insert the element x at the specified index and move the rest of the elements to the right.

list.index(x) - Searches for the value x in the list and returns the index of the element.

list.extend(listx) - It appends listx to the end of list.

list.remove(x) - Searches for the element x in list and removes the first instance of x.

list.pop(index) - removes and return the value at given index. If index is omitted the last element of the list is removed and returned.

list.count(x) - Counts the no. of times x appears in the list.

list.sort() - It sorts the list but one thing to notice is that it changes the original list.

list.reverse() - It reverses the whole list.

    
            a = [1, 3, 6, 9, 4, 2, 6]
            
            # creating a list b from user input
            b= []
            for i in range(2):
                k = int(input())
                b.append(k)
            #input by user :
            # 1
            # 9
            
            print(b)
            #output [1, 9]
            
            print(a)
            # output: [1, 3, 6, 9, 4, 2, 6]
            
            a.append(7)
            print(a)
            #output: [1, 3, 6, 9, 4, 2, 6, 7]
            
            a.insert(3, 8)
            print(a)
            #output: [1, 3, 6, 8, 9, 4, 2, 6, 7]
            
            print(a.index(6))
            #output: 2
            
            a.extend(b)
            print(a)
            #output: [1, 3, 6, 8, 9, 4, 2, 6, 7, 1, 9]
            
            a.remove(6)
            print(a)
            # output: [1, 3, 8, 9, 4, 2, 6, 7, 1, 9]
            
            a.pop()
            print(a)
            # output: [1, 3, 8, 9, 4, 2, 6, 7, 1]
            
            print(a.count(9))
            # output: 1
            
            a.sort()
            print(a)
            # output: [1, 1, 2, 3, 4, 6, 7, 8, 9]

            a.reverse()
            print(a)
            # output: [9, 8, 7, 6, 4, 3, 2, 1, 1]

    
    



COMMENTS