Python Programming Lists

What is list in python?

  • List is one of the compound data types which is used to contain collection of items of different data types.
  • List is versatile and comma-separated values (items) between square brackets.
  • Lists can be indexed and sliced.
  • Lists are a mutable type, i.e. it is possible to change their values.

List methods in python

append method

Adds a new element to the end of the list.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
list_var.append('six');                                                                                                                    
print list_var;  
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six']
This is also similar like
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
                                                                                
list_var[len(list_var):] = ['six'];                                             
print list_var; 
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six']
if you have used 'six' instead of ['six']
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
                                                                                
list_var[len(list_var):] = 'six';                                                                                                                             
print list_var;                                                                 
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 's', 'i', 'x']

extend method

Extend the list by adding all the items from another list or iterable data.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
                                                                                
list_var.extend(['six', 'seven']);                                              
print list_var;  
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
This is also equivalent like
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
                                                                                
list_var[len(list_var):] = ['six', 'seven'];                                    
print list_var;   
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six', 'seven']

insert method

insert a new element in specific index.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
list_var.insert(2, "3");                                                        
print list_var;                                                                 
Output:
$ python test_list.py 
['one', 'two', '3', 'three', 'four', 'five']
This is similar like append method when inserting element after last index.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'two', 'three',                                              
            'four', 'five'];                                                    
list_var.insert(len(list_var), "six");                                          
print list_var; 
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five', 'six']

remove method

removes first matching element in the list, otherwise raises error.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.remove('three');                                                       
print list_var;   
Output:
$ python test_list.py 
['one', 'two', 'three', 'four', 'five']
if specified element is not in the list, raises ValueError
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.remove('six');                                                         
print list_var;  
Raises error:
$ python test_list.py 
Traceback (most recent call last):
  File "test_list.py", line 5, in 
    list_var.remove('six');
ValueError: list.remove(x): x not in list

pop method

Removes element in the list at specified index and return that removed element. if no specified index, last element in the list is pop out.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
print list_var.pop(1);                                                          
print list_var;  
Output:
$ python test_list.py 
three
['one', 'two', 'three', 'four', 'five']

clear method

clears all elements in the list. this clear method for list is available from python 3.3, this will not work in python2.7.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.clear();                                                               
print(list_var);   
Output:
$ python3 test_list.py 
[]
This equivalent like below
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
del list_var[:];                                                                
print(list_var);  
or
del list_var[0:len(list_var)];
Output:
$ python test_list.py 
[]
if we use del list_name, deletes the entire list.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
del list_var;                                                                   
print(list_var);   
Output:
$ python test_list.py 
Traceback (most recent call last):
  File "test_list.py", line 6, in 
    print(list_var);
NameError: name 'list_var' is not defined

index method

Returns index of the soecified element in the list (or in the specified index range), otherwise raises ValueError. Syntax:
list.index(x[, start[, end]])
here start and end are index range to search.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
print(list_var.index('two'));                                                   
Output:
$ python test_list.py 
2
raises ValueError if specified value is not in the specified index range of list.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
print(list_var.index('two', 3, len(list_var))); 
raises error:
$ python test_list.py 
Traceback (most recent call last):
  File "test_list.py", line 5, in 
    print(list_var.index('two', 3, len(list_var)));
ValueError: 'two' is not in list

count method

Returns the number of occurrence of specified element in the list.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
print(list_var.count('three'));    
Output:
$ python test_list.py 
2

sort method

sorting the list elements. Syntax:
list.sort(key=None, reverse=False)
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.sort();                                                                
print list_var;   
Output:
$ python test_list.py 
['five', 'four', 'one', 'three', 'three', 'two']

sorted method

Returns a new sorted list from the items in iterable. Syntax:
sorted(iterable, *, key=None, reverse=False)
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
print sorted(list_var);                                                         
Output:
$ python test_list.py 
['five', 'four', 'one', 'three', 'three', 'two']

reverse method

Reverse the elements of the list in place (last index towards 0 index, not decending order).
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.reverse();                                                             
print list_var   
Output:
$ python test_list.py 
['five', 'four', 'three', 'two', 'three', 'one']
Decending order
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
list_var.sort(reverse=True);                                                    
print list_var    
or
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five']; 
list_var.sort();                                                    
list_var.reverse();                                                             
print list_var   
Output:
$ python test_list.py 
['two', 'three', 'three', 'one', 'four', 'five']

copy method

Return a shallow copy of the list. Equivalent to a[:]. copy method is also available in python 3.
#!/usr/bin/python                                                               
                                                                                
list_var = ['one', 'three', 'two', 'three',                                     
            'four', 'five'];                                                    
new_list = list_var.copy();                                                     
                                                                                
list_var[0] = "1";                                                              
print("old list: "+ str(list_var) +  ", new list: " + str(new_list));    
Output:
$ python3 test_list.py 
old list: ['1', 'three', 'two', 'three', 'four', 'five'], new list: ['one', 'three', 'two', 'three', 'four', 'five']

Using list as stack in python

Stack is last in first out.
append method is used to push the elements at last, pop method is used to return last element in the list default if no argument.
#!/usr/bin/python                                                               
                                                                                
stack_list = ['one', 'three', 'two'];                                           
print "stack: ", stack_list;                                                    
print "pop: ", stack_list.pop();                                                
print "push: 'four'";                                                           
stack_list.append("four");                                                      
print "pop: ", stack_list.pop();                                                
print "stack: ", stack_list;    
Output:
$ python test_list.py 
stack:  ['one', 'three', 'two']
pop:  two
push: 'four'
pop:  four
stack:  ['one', 'three']

Using list as queue in python

quue is first in first out, deque method is available in python to convert list as queue. popleft method is used to pop first in element of list. append is used to add element in last.
from collections import deque                                                   
#!/usr/bin/python                                                               
                                                                                
queue_list = deque(['one', 'three', 'two']);                                    
print "queue: ", queue_list;                                                    
print "pop: ", queue_list.popleft();                                            
print "push: 'four'";                                                           
queue_list.append("four");                                                      
print "pop: ", queue_list.popleft();                                            
print "queue: ", queue_list; 
Output;
$ python test_list.py 
queue:  deque(['one', 'three', 'two'])
pop:  one
push: 'four'
pop:  three
queue:  deque(['two', 'four'])

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^