Lists

Introduction

The purpose of Revision Tour Chapters is to brush up all concepts. This chapter is going to help you recall and brush up concepts of lists.

Lists in Python

A list is a standard data type of Python that can store a sequence of values belonging to any type. The lists are depicted through square brackets, e.g. following are some lists in Python:


    []                      #list with no member, empty list
    [1, 2, 3]               #list of integers
    [1, 2.5, 3.7, 9]        #list of number(integers and floating point)
    ['a', 'b', 'c']         #list of characters

Lists are mutable(i.e. modifiable), we can change elements of a list in place. List is one of the two mutable types of Python - Lists and Dictionaries are mutable types; all other data types of python are immutable.

Creating Lists


To create a list, put a number of expressions, separated by commas in square brackets. That is, to create a list you can write in the form given below.


            L= []
            L=[vlaue, ...]
        
This construct is known as a list display construct.
  • Creating Empty List
    :- The empty list is []. You can also create an empty list as:
    L= list()
  • Creating Lists from Existing Sequences
    :- You can also use the built-in list type object to create lists from sequences as per the syntax given below:
    L=list(<sequence>)

    where <sequence> can be any kind of sequence object including strings, tuples, and lists.
    Considering following examples:
    
                        >>>l1=list('hello')
                        >>>l1
                        ['h', 'e', 'l', 'l', 'o']
                    
  • Creating List from Keyboard Input
    :- You can also use this method of creating lists of single characters or single digits via keyboard input.
    Consider the code below:
    
                        >>>l1=list(input('Enter list elements:'))
                        Enter list elements: 234567
                        >>>l1
                        ['2', '3', '4', '5', '6', '7']
                    
    Notice this way the data type of all characters entered is string even though we entered digits. To enter a list of integers thought keyboard, you can use the method given below.
    Most commonly used method is eval(input()).

Lists vs. Strings


Lists and strings have a lot in commont yet key differences too. This section is going to summarize the similarities and differences between lists and strings.

Similarity between Lists and Strings


Length Function len(L) returns the number of items (count) in the list L.
Indexing and Slicing L[i] return the item at index i (the first item has index 0), and
L[i:j] returns a new list, containing the objects between i and j.
Membership operators Both 'in' and 'not in' operators work on Lists just like they work for other sequences such as strings. (Operators in tells if an element is present in the list or not, and not in does the opposite.)
Concatenation and Replication operators + and * The + operator adds one list to the end of another. The * operator repeats a list.
Accessing Individual Elements Like strings, the individual elements of a list are accessed through their indexes.
Consider following examples:
                        
                            >>>vowels = ['a','e', 'i', 'o', 'u']
                            >>>vowels[0]
                            'a'
                            >>>vowels[-1]
                            'u'
                        
                    

Difference between Lists and Strings


The list and strings are different from one another in following ways:
Storage: Lists are stored in memory exactly like strings, except that because some of their objects are larger than others, they store a reference at each index instead of single character as in strings.
Mutability: Strings are not mutable, while lists are. You cannot change individual elements of a string in place, but lists allow you to do so. That is, following statement is fully valid for Lists (though not for strings):

                
                    L[i] = <element>
                
            

For example, consider the same vowels list created above and have a look at following code:
                
                    >>>vowels[0] = 'A'
                    >>>vowels
                    ['A', 'e', 'i', 'o', 'u']
                    >>>vowels[-4] = 'E'
                    >>>vowels
                    ['A', 'E', 'i', 'o', 'u']
                
            

List Operations


In this section, we shall talk about most common list operations, briefly.

  • Traversing a List:
    Traversing a list means accessing and processing each element of it. The for loop makes it easy to traverse or loop over the items in a list, as per the following syntax:
                                
                                    for <item in <List>:
                                        #process each item here
                                
                            
    For example, following loop shows each item of a List L in separate lines:
    
                            L = ['P', 'y', 'y', 'h', 'o', 'n']
                            for a in L:
                                print(a)
                            
    Output:
    
                            P
                            y
                            t
                            h
                            o
                            n
                            
  • Joining Lists:
    The concatenation operator +, when used with two lists, joins two lists and returns the concatenated list. Consider the example given below:
                                
                                    >>>lst1 = [1, 4, 9]
                                    >>>lst2 = [6, 12, 20]
                                    >>>lst1 + lst2
                                    [1, 4, 9, 6, 12, 20]
                                
                            
    The + operator when used with lists requires that both the operands must be of list types.
  • Repeating or Replicating Lists:
    Like strings, you can use * operator to replicate a list specified number of times, e.g. (considering the same list lst1 = [1, 3, 5])
                               
                                   >>>lst1*3
                                   [1, 4, 9, 1, 4, 9, 1, 4, 9]
                               
                           
    Like strings, you can only use an integer with a * operator when trying to replicate a list.
  • Slicing the Lists:
    List slices, like string slices are the sub part of a list extracted out. You can use indexes of list elements to create list slices as per following format:
                                
                                    seq = L[start:stop]
                                
                            
    Consider the following example:
                                
                                    >>>lst = [10, 12, 14, 20, 22, 24, 30, 32, 34]
                                    >>>seq = lst[3:-3]
                                    >>>seq
                                    [20, 22, 24]
                                    >>>lst = [10, 12, 14, 20, 22, 24, 30, 32, 34]
                                    >>>lst[3:30]
                                    [20, 22, 24, 30, 32, 34]
                                    >>>lst [-15:7]
                                    [10, 12, 14, 20, 22, 24, 30]
                                
                            
    List also support slice steps too. That is, if you want to extract, not consecutive but every other element of the list, there is a way out - the slice steps. The slice steps are used as per following format:
                                
                                    seq = L[start:stop:step]
                                
                            
    Consider some examples to understand this. >>>lst [10, 12, 14, 20, 22, 24, 30, 32, 34] >>>lst[0:10:2] [10, 14, 22, 30, 34]

List Manipulation


You can perform various operations on lists like: appending, updating, deleting etc.
Appending Elements to a list: You can also add items to an existing sequence. The append() method adds a single item to the end of the list. It can be done as per the followign format

                
                    L.append(item)
                
            
Consider the following examples:
                
                    >>>lst1= [10, 12, 14]
                    >>>lst1.append(16)
                    >>>lst1
                    [10, 12, 14, 16]
                
            

Updating Elements to a list: To update or change an element of the list in place, you just have to assign a new value to the elements index in list as per the syntax:
                
                    L[index] = <new value>
                
            
Consider the following examples:
                
                    >>>lst1= [10, 12, 14, 16]
                    >>>lst1[2] = 24
                    >>>lst1
                    [10, 12, 24, 16]
                
            

Deleting Items form a list: You can also remove items from lists. The del statement can be used to remove an individual item, or to remove all items identified by a slice.
It is also used as per the syntax given below:
                
                    del List[<index>]            #remove elements at index
                    del List[<start>:<stop>]  #remove elements in list slice
                
            
Consider the following examples:
                
                    >>>del lst[10:15]
                    >>>lst
                    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 18]
                
            
If you use del <lstname> only, it will delete all the elements and the list object too. After this, no object by the name lst would be existing. You can also pop() method to remove single element, not slices. The pop() method is covered in a later section, List Functions.
Making True copy of a list Assignment with an assignment operator(=) on lists does not make a copy. Instead, assignment makes the two vaiables point to the one list in memory(called shallow copy). So if you make changes in one list, the other list will also report those changes because these two list-names are labels referring to same list because '=' copied the reference not the actual list.