What are lists?
*Container is an entity which contains multiple data items. It is also known as a collection or
a compound data type.
* Python has following container data types:
lists Tuples
Sets Dictionaries
* A list can grow or shrink during execution of the program. Hence it is also known as a
dynamic array. Because of this nature of lists they are commonly used for handling variable
length data.
* A list is defined by writing comma-separated elements within[ ].
num = [10, 25, 30, 40, 100]
names = [‘Sanjay’, ‘Anil’, Radha’, ‘Suparna’]
* List can contain dissimilar types, through usually they are a collection of similar types. For
example:
animal = [ ‘zebra’,155.55, 110]
2.
Accessing List Elements
*Entirelist can be printed just using the name of the list.
I = [’Able’, ‘was’, ‘I’, ‘ere’, ‘I’, ‘saw’, ‘elbA’]
print(l)
*Like strings, individual elements in a list can be accessed using indices. Hence, they are also known as sequence types. The index value starts from 0.
print(animals[1], ages[3])
*Like strings, lists can be sliced.
Print(animals[1:3])
print(ages[3:1])
* Items in a list can be repeated, i.e., a list may contain duplicate items. Like
printing,*can be used to repeat an element multiple times. An empty list is also feasible.
ages = [25, 26, 25, 27, 26,] #duplicates allowed
Num = [10]*5 #stores [10, 10 10, 10, 10]
lst = [ ] #empty list, valid
3.
Looping in Lists
*Ifwe wish to process each item in the list, we should be able to iterate through
the list. This can be done using a while or for loop.
animals = [‘zebra’, ‘Tiger’, ‘Lion’, ‘jackal’, ‘Kangaroo’]
#using while loop
i = 0
While i < len(animals);
print(animals[i])
I += 1
#using more convenient for loop
for a in animals:
print(a)
*While iterating through a list using a for loop, If we wish to keep track of index of
the element that a is referring to, we can do so using the built-in enumerate( )
function.
animals = [‘zebra’, ‘Tiger’, ‘Lion’, ‘jackal’, ‘Kangaroo’]
for index, a in enumerate(animals):
print(index, a)
4.
Basic List Operations
*Mutually– unlike strings, lists are mutable (changeable). So, list can be updated as shown
below:
animals = [‘zebra’, ‘Tiger’, ‘Lion’, ‘jackal’, ‘Kangaroo’]
ages = [25, 26, 27, 28, 25]
animals[2] = Rhinoceros’.
ages[5] = 31
Ages[2:5] = [24, 25, 32] # sets items 2 to 4 with values 24,25
Ages[2:5] = [ ] # delete items 2 to 4
5.
*Concatenation - Onelist can be concatenated (appended) at the end of
another as shown below:
Ist = [12, 15, 13, 23, 22, 16, 17]
lst = lst + [33, 44, 55]
print(lst) # prints [12, 15, 13, 23, 22, 16, 17, 33, 44, 55]
*Merging-Two lists can be merged to create a new list.
S = [10, 20, 30]
t = [100, 200, 300]
z = s+t
print(z) # prints [10, 20, 30, 100, 200, 300]
*Conversion- A string/tuple/set can be converted into a list using the list() conversion
function.
1 = list('Africa") #converts the string to a list ['A', 'f', 'r', ‘i', 'c', 'a‘]
6.
*Aliasing - Onassigning one list to another, both refer to the same list. Changing one
changes the other. This assignment is often known as shallow copy or aliasing.
Ist1= [10, 20, 30, 40, 50]
Ist2 = Ist1 # doesn't copy list. Ist2 refers to same list as Ist1
print(Ist1) # prints [10, 20, 30, 40, 50]
print(Ist2 # prints (10, 20, 30, 40, 50]
Ist1[0]=100
print(Ist1[0], Ist2[0]) # prints 100 100
*Cloning - This involves copying contents of one list into another. After copying both refer to
different lists, though both contain same values. Changing one list, does not change another.
This operation is often known as deep copy.
Ist = [10, 20, 30, 40, 50]
lst2 = [ ] #empty list
Ist2 = Ist2 + Ist1 #Ist1, Ist2 refer to different lists
print(lst1) # prints [10, 20, 30, 40, 50
print(Ist2) # prints [10, 20, 30, 40, 50]
Ist1[0]=100
print(lst[0], Ist2[0]) # prints 100, 10
7.
*Searching - Anelement can be searched in a list using the in membership operator as
shown below:
Ist = ['a', 'e', ‘i', 'o', 'u‘]
res = 'a' in Ist #return True since 'a' is present in list
res = ‘z’ not in Ist #return True since 'z' is absent in list
*Identity - Whether the two variables are referring to the same list can be checked using the is identity
operator as shown below:
Ist1 = [10, 20, 30, 40, 50]
Ist2 = [10, 20, 30, 40, 50]
Ist3 = Ist1
print(Ist1 is Ist2) # prints False
print(Ist1 is Ist3) # prints True
print(Ist1 is not Ist2) # prints True
*Note the difference for basic types like int or str :
num1 = 10
num2 = 10
s1 = 'Hi‘
s2= 'Hi‘
print(num1 is num2) # prints True
print(s1 is s2) # prints True
8.
*Comparison - Itis possible to compare contents of two lists.
Comparison is done item by item till there is a mismatch. In the following code it would be
decided that a is less than b when 3 and 5 are compared.
a = [1, 2, 3, 4]
b = [1, 2, 5]
print(a < b) # prints True
*Emptiness - We can check if a list is empty using not operator.
Ist = [ ]
if not Ist : # Ist returns False
print('Empty list')
Alternately, we can convert a list to a bool and check the result.
lst = [ ]
print(bool(lst)) #prints Flase
*Also note that the following values are considered to be Flase:
None
Number equivalent to zero: 0, 0.0, 0j
Empty string, list and tuple: ‘ ’,””,[ ],( )
Empty set and dictionary: { }
9.
USING BUILT-IN FUNCTIONSON LISTS
*Many built-in functions can be used with lists.
len(lst) #return number of items in the list
max(lst) #return maximum element in the list
min(lst) #return minimum element in the list
Sum(lst) #return sum of all elements in the lists
any(lst) #return True if any elements of lst is True
all(lst) #return True if all elements of lst are True
del( ) #deletes elements or slice or entire list
Sorted(lst) #return sorted list, lst remains unchanged
reversed(lst) #used for reversing lst
Except the last 3 , other functions are self explanatory. sorted( ) and reversed( ) are
discussed below.
10.
del( ) function’susage is shown below:
lst = [10,20,30,40,50]
lst = del(lst[3]) #delete 3rd
item in the list
del(lst[2:5]) #delete items 2 to 4 from the list
del(lst[:]) #delete the entire list
lst = [] #another way to delete an entire list
*If multiple variables are referring to same list, then deleting one does not delete the others.
lst = [10,20,30,40,50]
lst3 = lst2=lst1 #all refer to same list
Lst1 = [ ] #lst1 refers to empty list; lst2, lst3 to original list
print(lst2) #prints [10,20,30,40,50]
print(lst3) #prints [10,20,30,40,50]
*If multiple variables are referring to same list and we wish to delete all ,we can do so as
shown below:
Lst2[ ] = [ ] #lists is emptied by deleting all items
print(lst2) #prints [ ]
print(lst3) #prints [ ]
11.
List Methods
Any listis an object of type list. Its methods can be accessed using the syntax Ist.method( ).
Usage of some of the commonly used methods is shown below:
Ist = [12, 15, 13, 23, 22, 1l6, 17] # create list
Ist.append(22) #add new item at end
lst.remove(13) # delete item 13 from list
lst.rermove(30) # reports valueError as 30 is absent in Ist
lst.pop( ) # removes last item in list
Ist.pop(3) # removes 3rd item in the list
Ist.insert(3, 21) # insert 21 at 3rd position
Ist.count(23) # return no. of times 23 appears in lst
idx = Ist.index(22) # return index of item 22
idx = Ist.index(50) #reports valueError as 50 is absent in lst
12.
Sorting and Reversing
*Usageof list methods for reversing a list and for sorting is shown below:
Ist = (10, 2, 0, 50, 4)
Ist.reverse( )
print(lst) # prints [4, 50, 0, 2, 10)
Ist.sort( )
print(lst) # prints [0, 2,4, 10, 50)
Ist.sort(reverse =True) #sort items in reverse order
print(lst) # prints (50, 10, 4, 2,0)
Note that reverse( ) and sort( ) do not return a list. Both manipulate the list in place.
*Usage of built-in functions for reversing a list and for sorting is shown below:
lst = [10, 2, 0, 50, 4]
print(shorted(lst)) # prints [0, 2, 4, 10, 50]
print(shorted(lst, reverse = true)) # prints [50, 10, 4, 2, 0]
print(list(reversed(lst))) # prints [4, 50, 0, 2, 10]
13.
Note that sorted() function returns a new sorted list and keeps the original list
unchanged, Also, reversed( ) function returned a list returns a list_reverseiterator
object which has to converted into a list using list( ) to get a reversed list.
*Reversal is also possible using a slicing operation as shown below
lst = [10, 2, 0, 50, 4]
print(lst)[::-1]) # prints [4, 50, 0, 2, 10]
List varieties
*It is possible to create a list if lists (nested lists).
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
c = [a, b]
Print(c[0][0], c[1][2]) # 0th
element of 0th
list, 2nd
ele. Of 1st
list
14.
*A list maybe embedded in another list.
x = [1, 2, 3, 4]
y = [10, 20, x, 30]
print(y) # outputs [10, 20, [1, 2, 3, 4], 30]
*It is possible to unpack a string or list within a list using the * operator.
S = ‘Hello’
l = [*s]
print(l) # outputs [‘H’, ‘e’, ‘l’, ‘l’, ‘o’]
x = [1, 2, 3, 4]
y = [10, 20, *x, 30]
print(y) # outputs [10, 20, 1, 2, 3, 4, 30]
15.
Stack Data Structure
*Adata structure refers to an arrangement of data in memory popular data structures
are stack, queue, tree, graph and map.
*Stack is a last in first out (UFO) list, i.e., last element that is added to the list is the first
element that is removed from it.
*Adding an element to a stack is called push operation and removing an element from
it is called pop operation. Both these operations are carried out at the rear end of the
list.
*Push and pop operations can be carried out using the append( ) and pop( ) methods
of list object. This is demonstrated in program 8.3
16.
Queue Data Structure
*Queueis a first in first out (FIFO), i.e.., first element that is added to the list is the first
element that is removed from it.
*Lists are not efficient for implementation of queue data structure.
*With lists removal of items from beginning is not efficient, since involves shifting of rest
of the elements by 1 position after deletion.
*Hence for fast additions and deletion, deque class of collections module is preferred.
*Deque stands for double ended queue, Addition and deletion in a deque can take
place at both ends.
*Usage of deque class to implement a queue data structure is demonstrated in
program 8.4.