Python Programming Made Easy (2016)
Chapter 6: Lists
Lists are the simplest data structure in Python and are used to store a list of values. Lists are collections of items (strings, integers, or even other lists). Each item in the list has an assigned index value. Lists are enclosed in [ ]. Each item in a list is separated by a comma. Unlike strings, lists are mutable, which means they can be changed.
List operations
Function |
Description |
Example |
Creation |
Lists are created using a comma separated list of values surrounded by square brackets. Lists hold a sequence of values. Lists are very easy to create, these are some of the ways to make lists. |
L = [ ] # An empty list is created using only square brackets list1 = [‘one’, ‘two’, ‘three’, ‘four’, ‘five’] numlist = [1, 2,3,4,5] |
Length |
With the length function we can get the length of a list |
list = ["1", "hello", 2, "world"] len(list) 4 |
Append |
List append will add the item at the end. list.append(x) will add an element to the end of the list |
list = [ 'Python','Java','C++'] list.append('C') print list ['Python', 'Java', 'C++', 'C'] |
Insert |
If we want to add at the beginning or middle, we can use the insert function. |
list.insert(0, "HTML") print list ['HTML', 'Python', 'Java', 'C++', 'C'] list.insert(3, "VB") print list ['HTML', 'Python', 'Java', 'VB', 'C++', 'C'] |
Remove |
To remove an element's first occurrence in a list, simply use list.remove. The syntax is: list.remove(x). x can be the item name. x can also be a number. |
list = ['HTML', 'Python', 'Java', 'VB', 'C++','C'] list.remove("Java") print list ['HTML', 'Python', 'VB', 'C++', 'C'] list = [1,2,3,4] list.remove(2) print list [1,3,4] |
Delete |
We use del to remove item based on index position. |
list = ['HTML', 'Python', 'Java', 'VB', 'C++','C'] del list[1] print list HTML, Java, VB,C++,C |
Extend |
It joins a list with another |
list2 = ["Javascript", "VBScript"] list.extend(list2) print list ['HTML', 'VB', 'C++', 'C', 'Javascript', 'VBScript'] |
In |
The keyword "in" can be used to test if an item is in a list. |
list = ["red", "orange", "green", "blue"] if "red" in list: print “red is present in list” red is present in list |
Not in |
Keyword "not" can be combined with "in". |
list = ["red", "orange", "green", "blue"] if "purple" not in list: print “purple not in list” purple not in list |
Reverse |
The reverse method reverses the order of the entire list. |
#To print a reverse list L = [10,20,40] for i in list[::-1]: print i #OR L.reverse() print L [40,20,10] |
Sorting |
It takes a list and returns a new list with those elements in sorted order. The original list is not changed. The sorted() function can be customized though optional arguments. The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards. |
#create a list with some numbers in it numbers = [5, 1, 4, 3, 2, 6, 7, 9] #prints the numbers sorted print sorted(numbers) #the original list of numbers are not changed print numbers [1,2,3,4,5,6,7,9] |
Split |
Split each element in a list |
list = 'one, two, three, four, five' newlist = list.split(',') print newlist ['one', ' two', ' three', ' four', 'five'] |
Indexing |
Each item in the list has an assigned index value starting from 0. Accessing elements in a list is called indexing. |
list = ["apple", "banana", "mango"] list[0] == "apple" list[1] == "banana" list[2] == "mango" |
Slicing
Accessing parts of segments is called slicing. Lists can be accessed just like strings by using the [ ] operators. The key point to remember is that the : end value represents the first value that is not in the selected slice. So, the difference between end and start is the number of elements selected (if step is 1, the default).
Let's create a list with some values in it
colors = ['yellow', 'red', 'blue', 'green', 'black']
print colors[0]
Yellow |
print colors [1:]
red, blue, green, black |
a[start:end] # items start through end -1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above
a[start:end:step] # start through not past end, by step
Negative indexing
The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning.
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Calls to list methods have the list they operate on appear before the method name. Any other values the method needs to do its job is provided in the normal way as an extra argument inside the round brackets.
The following figure helps to demonstrate negative indices
List functions
S.No |
Function |
Description |
1 |
cmp(list1, list2) |
Compares elements of both lists. |
2 |
len(list) |
Gives the total length of the list. |
3 |
max(list) |
Returns item from the list with max value. |
4 |
min(list) |
Returns item from the list with min value. |
5 |
list(seq) |
Converts a tuple into list. |
6 |
list.append(obj) |
Appends object obj to list |
7 |
list.count(obj) |
Returns count of how many times obj occurs in list |
8 |
list.extend(seq) |
Appends the contents of seq to list |
9 |
list.index(obj) |
Returns the lowest index in list that obj appears |
10 |
list.insert(index,obj) |
Inserts object obj into list at offset index |
11 |
list.pop(obj=list[-1]) |
Removes and returns last object or obj from list |
12 |
list.remove(obj) |
Removes object obj from list |
13 |
list.reverse() |
Reverses objects of list in place |
14 |
list.sort([func]) |
Sorts objects of list, use compare func if given |
Table 6.1: Summary of list functions and methods
Matrices
A matrix is a grid, with each location in the grid containing some information. Consider the excel sheet. A matrix has rows and columns and each element is inside a cell. To uniquely identify the element we use the row name and column name.
Fig 6.1: Matrix – excel
To access “2”, we say B1 in Spreadsheet, where B is the column header and 1 is the row. In a computer, we store the matrix and access the elements using indices.
0 |
1 |
2 |
|
0 |
1 |
2 |
3 |
1 |
4 |
5 |
6 |
Fig 6.2: Matrix – 2D Array
To access “2”, we say [0][1].
Matrix implementation using list
We can implement matrix operation using list. Matrix operation can be implemented using nested list. List inside another list is called nested list.
As a first step, we need to get the number of rows and columns.
m=int(raw_input ("Enter total number of rows")) n=int (raw_input ("Enter total number of columns")) |
After that we can create a matrix named a, as stated below.
a=[[random.random()for row in range(m1)]for col in range(n1)] |
We need to import random file. This step generates a matrix like the one listed below if we enter values for number of rows and columns as 2. It is also filled with some random values as shown in fig below.
0.314 |
0.678 |
0.191 |
0.567 |
Fig 6.3: List- Initial state
We can fill the matrix with values from the user.
for i in range(m): for j in range(n): l[k]=int(raw_input(("Enter element"))) |
1 |
2 |
3 |
4 |
Fig 6.4: List- with values
Finally, we can print the values with the below code.
for i in range(m): for j in range(n): print l[k],'\t', k=k+1 |
Example 6.1: Write a program to input any matrix with mXn, and print the number on the output screen in matrix format. m=int(raw_input ("Enter total number of rows")) n=int (raw_input ("Enter total number of columns")) l=range (m*n) k=0 print "Input all matrix elements one after other" for i in range(m): for j in range(n): l[k]=int(raw_input(("Enter new element"))) k=k+1 print "output is" k=0 for i in range(m): for j in range(n): print l[k],'\t', k=k+1 |
Solved Questions
1. Write a program to use list functions to sort a list and find the maximum and minimum marks in a class.
Ans:
print "Enter Number of Marks: ",
maxrange = 0
maxrange = input()
i = 0
marks = []
for i in range(0, maxrange):
marks.append(input())
# Sort the marks
marks.sort()
for i in range (0,maxrange):
print marks[i]
print "Highest score is",max(marks)
print "Lowest score is", min(marks)
print "Class Average is", sum(marks)/maxrange
2. Write a program to input any two matrices and print sum of matrices.
Ans:
import random
m1=int(raw_input ("Enter total number of rows in the first matrix") )
n1=int(raw_input ("Enter total number of columns in the first matrix") )
a=[[random.random()for row in range(m1)]for col in range(n1)]
for i in range(m1):
for j in range(n1):
a[i][j]=int(raw_input("? ") )
m2=int(raw_input ("Enter total number of rows in the first matrix") )
n2=int(raw_input ("Enter total number of columns in the first matrix") )
b=[[random.random()for row in range(m2)]for col in range(n2)]
for i in range(m2):
for j in range(n2):
b[i][j]=int(raw_input("? ") )
c=[[random.random()for row in range(m1)]for col in range(n1)]
if ((m1==m2) and (n1==n2)):
print "output is"
for i in range(m1):
for j in range(n1):
c[i][j]=a[i][j]+b[i][j]
print c[i][j],'\t',
else:
print "Matrix addition not possible"
3. Write a program to input any two matrices and print product of matrices.
import random
m1=int(raw_input ("Enter total number of rows in the first matrix") )
n1=int(raw_input ("Enter total number of columns in the first matrix") )
a=[[random.random()for row in range(m1)]for col in range(n1)]
for i in range(m1):
for j in range(n1):
a[i][j]=int(raw_input("? ") )
m2=input("Enter total number of rows in the second matrix")
n2=input("Enter total number of columns in the second matrix")
b=[[random.random()for row in range(m2)]for col in range(n2)]
for i in range(m2):
for j in range(n2):
b[i][j]=int(raw_input("? ") )
c=[[random.random()for row in range(m1)]for col in range(n2)]
if (n1==m2):
for i in range(m1):
for j in range(n2):
c[i][j]=0
for i in range(m1):
for j in range(n2):
for k in range(n1):
c[i][j]+=a[i][k]*b[k][j]
print c[i][j],'\t',
else:
print "Multiplication not possible"
4. Write a program to input any matrix and print both diagonal values of the matrix.
m=int(raw_input ("Enter total number of rows"))
n=int (raw_input ("Enter total number of columns"))
l=range (m*n)
k=0
print "Input all matrix elements one after other"
for i in range(m):
for j in range(n):
l[k]=int(raw_input(("Enter new element")))
k=k+1
print "left diagonal"
k=0
for i in range(m):
for j in range(n):
if i == j:
print l[k],'\t',
else:
print '\t',
k=k+1
print "right diagonal"
k=0
for i in range(m):
for j in range(n):
if (i+j) == (m-1):
print l[k],'\t',
else:
print '\t',
k=k+1
5. Write a program to pass any list and to arrange all numbers in descending order.
def arrange (l,n):
for i in range(n-1):
for j in range(n-i-1):
if l[j]<l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
def main():
l=[7,5,8,2,9,10,3]
arrange (l,len(l))
print l
if __name__ == "__main__":
main()
Practice problems
1. Write a program to calculate and display the sum of all the odd numbers in the list.
2. Write a program for finding a matrix rowsum, column sum and diagonal sum.
3. Define a function overlapping ( ) that takes two lists and returns True if they have at least one member in common, False otherwise.
4. Write the output from the following code:
A=[20,40,60,80,100] L=len(A) S=0 for I in range(1,L,2): S+=A[I] print "Sum=",S |
5. Find the errors from the following program
n=int(raw_input ("Enter total number of elements") ) l=range(n) print l for i in (n): l[i]=raw_input("enter element") print "All elements in the list on the output screen" for i on range(n): print l[i] |
6. Write a function to find all duplicates in the list.