Professional Documents
Culture Documents
4.1 LISTS
A list is an ordered set of values (any type), where each value is identified by an index.
It can be created as a set of values separated by commas within square brackets.
The values in a list are called elements or items.
Example
list1=[10, 20, 30, 40]
list2=['white ‘, 'black’, 'red']
list3=[10,'white',8.4]
Indexing Lists:
Each item in a list corresponds to an index number, which is an integer value, starting
with the index number 0.
Any integer expression can be used as an index.
If you try to read or write an element that does not exist, you get an IndexError.
If an index has a negative value, it counts backward from the end of the list.
Example:
t=[10,20,30,40,50]
negative index -5 -4 -3 -2 -1
t 10 20 30 40 50
positive index 0 1 2 3 4
4.1.2 Accessing Items in List:
Item of the list can be accessed by referring its index number.
Example:
>>>t=[10, 20, 30, 40,50]
>>>t[1]
20
4.1.3 Modifying Items in List:
We can use indexing to change items within the list, by setting an index number equal
to a different value.
Example:
>>>t=[10, 20, 30, 40,50]
>>>t[1]=200
>>>t
[10,200,30,40,50]
4.1.4 Removing an Item from a List:
Items can be removed from lists by using the del statement. This will delete the value
at the specified index number within the list.
Example:
>>>t=[10,20,30,40,50]
>>>del t[3]
>>>t
[10,20,40,50]
Methods Description
append() Adds an element to the end of the list
extend() Add all contents of the second list to the first list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
index() Returns the index of the first matched element
count() Returns the number of occurrences of an element
specified in the list
sort() Sort items in a list in an ascending order
reverse() Reverse the order of items in the list
PPG INSTITUTE OF TECHNOLOGY Page 4
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
4.4.1 append()
Adds an element to the end of the list
Syntax:
list.append(element)
Example:
mylist=['cake', 'cooldrinks']
mylist.append('milk')
print('after appending')
print(mylist)
Output:
after appending
['cake', 'cooldrinks', 'milk']
4.4.2 extend()
Add all contents of the second list to the first list
Syntax:
list.extend(secondlistname)
Example:
mylist=['cake', 'cooldrinks']
newlist=['milk']
print('before extending',mylist)
mylist.extend(newlist)
print('after extending', mylist)
Output:
before extending ['cake', 'cooldrinks']
after extending ['cake', 'cooldrinks', 'milk']
4.4.3 insert()
Insert an item at the defined index
Syntax:
list.insert(index,element)
Example:
PPG INSTITUTE OF TECHNOLOGY Page 5
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
mylist=['cake', 'cooldrinks']
print('before inserting',mylist)
mylist.insert(1,'milk')
print('after inserting', mylist)
Output:
before inserting ['cake', 'cooldrinks']
after inserting ['cake', 'milk', 'cooldrinks']
4.4.4 remove()
Removes an item from the list
Syntax:
list.remove(element)
Example:
mylist=['cake', 'cooldrinks','milk','jam']
print('before removing',mylist)
mylist.remove('milk')
print('after removing', mylist)
Output:
before removing ['cake', 'cooldrinks', 'milk', 'jam']
after removing ['cake', 'cooldrinks', 'jam']
4.4.5 pop()
Removes and returns an element at the given index
Syntax:
list.pop(index)
Example:
mylist=['cake', 'cooldrinks','milk','jam']
print('before poping',mylist)
mylist.pop(2)
print('after poping', mylist)
Output:
before poping ['cake', 'cooldrinks', 'milk', 'jam']
after poping ['cake', 'cooldrinks', 'jam']
4.4.6 clear()
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Syntax:
listname.sort(element)
Example:
mylist=['cake','tea', 'cooldrinks','milk','jam']
print('before sorting',mylist)
mylist.sort()
print('After sorting',mylist)
Output:
before sorting ['cake', 'tea', 'cooldrinks', 'milk', 'jam']
After sorting ['cake', 'cooldrinks', 'jam', 'milk', 'tea']
4.4.10 reverse()
Reverse the order of items in the list
Syntax:
list.reverse()
Example:
mylist=['cake','tea', 'cooldrinks','milk','jam']
print('before reversing',mylist)
mylist.reverse()
print('After reversing',mylist)
Output:
before reversing ['cake', 'tea', 'cooldrinks', 'milk', 'jam']
After reversing ['jam', 'milk', 'cooldrinks', 'tea', 'cake']
4.4.11 Example Program for the usage of List Methods:
mylist=[10, 20]
mylist.append(30)
print('1.APPEND METHOD')
print(mylist)
newlist=[40]
print('2.EXTEND METHOD')
print('before extending',mylist)
mylist.extend(newlist)
print('after extending', mylist)
PPG INSTITUTE OF TECHNOLOGY Page 8
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
print('3.INSERT METHOD')
print('before inserting',mylist)
mylist.insert(1,15)
print('after inserting', mylist)
print('4.REMOVE METHOD')
print('before removing',mylist)
mylist.remove(15)
print('after removing', mylist)
print('5.POP METHOD')
print('before poping',mylist)
mylist.pop(2)
print('after poping', mylist)
print('6.INDEX METHOD')
print('The index is at ',mylist.index(20))
print('7.COUNT METHOD')
print(mylist.count(20))
print('8.SORT METHOD')
print('before sorting',mylist)
mylist.sort()
print('After sorting',mylist)
print('9.REVERSE METHOD')
print('before reversing',mylist)
mylist.reverse()
print('After reversing',mylist)
print('10.CLEAR METHOD')
print('before clearing',mylist)
mylist.clear()
print('after clearing', mylist)
OUTPUT:
1.APPEND METHOD
[10, 20, 30]
2.EXTEND METHOD
before extending [10, 20, 30]
PPG INSTITUTE OF TECHNOLOGY Page 9
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
tea
cooldrinks
milk
jam
10
20
30
40
50
4.6 LIST MUTABILITY
Lists are mutable i.e., we can able to add/delete /replace any value in the list at any
time.
The slice operator on the left side of an assignment operation can update single or
multiple elements of a list.
New elements can be added using append() method
The elements can be delete using pop() method
Syntax:
mylist[index]=value
Program:
mylist=[5,8,56,45,7,87]
print('Old list values are', mylist)
mylist[4]=70
print('New list values are',mylist)
Output:
Old list values are [5, 8, 56, 45, 7, 87]
New list values are [5, 8, 56, 45, 70, 87]
4.7 ALIASING
If mylist is a list object which holds data and mylist is assigned to newlist, then both
variable refer to same object.
mylist
[1,2,3]
newlist
An object with more than one reference and one name is called aliased
Alaised object is mutable in nature
Example:
mylist=[1,2,3]
PPG INSTITUTE OF TECHNOLOGY Page 12
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
newlist=mylist
print('mylist values are:', mylist)
print('newlist values are:', newlist)
mylist[0]=1000
print('mylist values are:', mylist)
print('newlist values are:', newlist)
Output:
mylist values are: [1, 2, 3]
newlist values are: [1, 2, 3]
mylist values are: [1000, 2, 3]
newlist values are: [1000, 2, 3]
mylist
[1000,2,3]
newlist
oldlist
[10,20,30,40,50]
newlist
cloning
oldlist [10,20,30,40,50]
newlist [10,20,30,40,50]
Method 2:
copy.copy() function:
copy.copy() function is little slower than list() since it has to determine data
type of oldlist first
Syntax:
newlist=copy.copy(oldlist)
Program:
import copy
oldlist=[10,20,30,40,50]
newlist=copy.copy(oldlist)
print('The old list is',oldlist)
PPG INSTITUTE OF TECHNOLOGY Page 14
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Passing a list as an argument actually passes a reference to the list, not a copy or clone
of the list.
When a list is passed as a parameter to a function, the function gets a reference to the
list.
Example 1: Insert the element in the list
def insert(t): #function defintion
t.insert(1,15) #inserts the new element 15 at the index 1
mylist=[10,20,30,40,50]
print('Before calling the insert function',mylist)
insert(mylist) #function call
print('After calling the insert function',mylist)
Output:
Before calling the insert function [10, 20, 30, 40, 50]
After calling the insert function [10, 15, 20, 30, 40, 50]
Example 2: Creates and returns a new list
def display(t): #function defintion
return t[:]
mylist=[10,20,30,40,50]
print('mylist is:',mylist)
newlist=display(mylist) #function call
print('newlist is',newlist)
Output:
mylist is: [10, 20, 30, 40, 50]
newlist is [10, 20, 30, 40, 50]
4.10 TUPLES
A tuple is a sequence of immutable Python objects i.e. the tuples cannot be changed
unlike lists.
Tuples use parentheses to represent it.
Syntax:
var_name=(element1,element2,…elemntn)
Example:
tuple=(1,2,3,4,5,6,7,8)
The elements of a list don’t have to be the same type
tuple=(‘gold’,454,5.3,4)
We can also create empty tuple as follows
tuple1=()
Empty tuple can also be created using tuple() function as follows:
t=tuple()
Creating tuple from string:
string="hello"
print('the string are', string)
mytuple=tuple(string)
print('strings converted to tuples',mytuple)
Output:
the string are hello
strings converted to tuples ('h', 'e', 'l', 'l', 'o')
Creating tuple from list
list=['w','e','l','c','o','m','e','to','python']
print('The lists are', list)
mytuple=tuple(list)
print('list converted to tuples',mytuple)
Output:
The lists are ['w', 'e', 'l', 'c', 'o', 'm', 'e', 'to', 'python']
list converted to tuples ('w', 'e', 'l', 'c', 'o', 'm', 'e', 'to', 'python')
Creating tuple from keyboard input:
mytuple=tuple(input('Enter tuple elements'))
print (mytuple)
Output:
Enter tuple elements 123abc
('1', '2', '3', 'a', 'b', 'c')
Example Program:
newtuple = ('p','r','o','g','r','a','m')
print(newtuple[0]) # to accesss the 1st element
print(newtuple[6]) # to access the 7 th element
print(newtuple) # to access the original list
print(newtuple[-1]) # to access the last item in the list
Output:
p
m
('p', 'r', 'o', 'g', 'r', 'a', 'm')
m
4.10.2.2 Slicing
Slicing operator [: ] is used to access the range of items in the tuple.
Syntax:
Tuplename[start:finish-1]
Where
Tuplename ->user defined name
Start->index of the initial character of the substring
Finish->index of the ending character of the substring
Program:
newtuple = ('p','r','o','g','r','a','m')
print(newtuple[2:6])
print(newtuple[2:])
print(newtuple[:4])
Output:
('o', 'g', 'r', 'a')
('o', 'g', 'r', 'a', 'm')
('p', 'r', 'o', 'g')
(2,3,4,5)
4.10.2.5 Traverse
The most common way to traverse the elements of a tuple is with a for loop.
Example:
t=(1,2)
for i in t:
print(i)
Output:
1
2
temp = a
a=b
b = temp
(a,b) = (b,a)
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
PPG INSTITUTE OF TECHNOLOGY Page 20
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
All the expressions on the right side are evaluated before any of the assignments.
Naturally, the number of variables on the left and the number of values on the right
have to be the same.
>>>(a,b,c,d)=(1,2,3)
ValueError: need more than 3 values to unpack
Example Program
Swapping of two numbers
a=input("Enter the value of a")
b=input("Enter the value of b")
print("Value of a and b before swapping",a,b)
(a,b)=(b,a)
print("Value of a and b after swapping",a,b)
Output:
Enter the value of a 10
Enter the value of b 20
Value of a and b before swapping 10 20
Value of a and b after swapping 20 10
print (mytuple)
Output:
Quotient and Remainder is:
(2, 1)
4.13 DICTIONARIES:
A dictionary contains a collection of indices, which are called keys, and a collection
of values.
Each key is associated with a single value. The association of a key and a value is
called a key-value pair or sometimes an item.
A Dictionary may contain any data type and is mutable.
Its keys, however, are mutable and can only be a string, tuple or a number. Values
stored on a dictionary can only be accessed through the keys.
1. Creating a Dictionary:
There are several ways to create a new list; the simplest is to enclose the elements in
squiggly-brackets { }.
In addition to the curly braces, there are also colons (:) throughout the dictionary.
Syntax:
#To create an empty dictionary:
dict= {}
#To create a dictionary with key-value pairs:
dict={key1:value1,key2:vlaue2,key3=value3}
key = User defined variable names
value= Values assigned for the key
Example
Book = { Name: ‘Programming in C’, Price:1000 }
The function dict creates a new dictionary with no items.
>>>d=dict()
>>>d
{}
2. Accessing Elements on a Dictionary:
PPG INSTITUTE OF TECHNOLOGY Page 22
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
A Dictionary is an unordered data type. Hence we can’t use the indexing operator to
access the values. We will have to use the key to access the associated value.
To access dictionary elements, We can either place the keys [] inside square brackets
or use the get() method.
Example 1
# To access data by using the keys:
>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}
>>>my_dict ['Name']
'Sachin'
>>>my_dict ['Class']
'First'
Example 2
# To access the same values with the get() method :
>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}
>>>my_dict.get ('Name')
>>>my_dict.get ('Class')
Output
'Sachin'
'First'
3. Adding and Modifying Entries To A Dictionary
A dictionary can be updated by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
i) Adding Dictionary Entries
Python evaluates the new entry and checks if there is the similar key in the current
dictionary.
If there is none, then it appends the key: value pair.
If the key already exists, then it updates the value of the existing key.
Syntax:
dict_name [key]=b
Where b is the key-value pair to be the dict_name dictionary.
Example:
# To add a new key-value pair, to the already existing dictionary
PPG INSTITUTE OF TECHNOLOGY Page 23
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
Output:
Traceback (most recent call last):
File "python", line 3, in <module>
NameError: name 'my_dict' is not defined
Output:
dict_keys([1, 2])
2. values():
The values() method returns a view object that displays a list of all values in a given
dictionary.
Example:
d={1:'one',2:'two'}
print(d.values())
Output:
dict_values(['one', 'two'])
3. items():
The items() method returns a view object that displays a list of a given dictionary's
(key, value) tuple pair.
Example:
d={1:'one',2:'two'}
print(d.items())
Output:
dict_items([(1, 'one'), (2, 'two')])
4. clear():
PPG INSTITUTE OF TECHNOLOGY Page 25
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
7. get():
The get() method returns the value for the specified key if key is in dictionary.
Example:
d={1:'one',2:'two'}
print(d.get(1,"Not found"))
print(d.get(3,"Not found"))
Output:
one
Not found
PPG INSTITUTE OF TECHNOLOGY Page 26
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
8. setdefault():
The method setdefault() is similar to get(), but will set dict[key]=default if key is not
already in dict.
Syntax
dict.setdefault(key, default=None)
Parameters
key − This is the key to be searched.
default − This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key
is not available then it will return provided default value.
Example:
>>>my_dict={'a': 'car', 'b': 'van', 'c': 'bus'}
>>>my_dict.setdefault('c',None)
Output:
bus
9.update():
The update() method adds element(s) to the dictionary if the key is not in the
dictionary. If the key is in the dictionary, it updates the key with the new value.
Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
Output:
{1: "one", 2: "two"}
10. popitem()
The popitem () method is used to remove a random key-value pair from a dictionary.
The method does not take an argument and returns the deleted key-value pair.
Example:
>>>my_dict = {'Ocean': 'Indian Ocean', 'Sea': 'Arabian', 'river': 'Cauvery'}
PPG INSTITUTE OF TECHNOLOGY Page 27
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]
>>>my_dict.popitem ()
>>>my_dict #Updated Dictionary
Output:
{'Ocean': 'Indian Ocean', 'Sea': 'Arabian'}
S
Function Description Example Output
No
1 len() Returns the dict = {'Name': 'Zara', 'Age': 7}; Length : 2
number of items print ("Length : %d" % len(dict))
in the dictionary
2 str() Returns a ict = {'Name': 'Zara', 'Age': 7}; Equivalent String :
printable string print ("Equivalent String : %s" {'Name': 'Zara', 'Age':
representation of % str (dict)) 7}
a dictionary
3 type() Returns the type dict = {'Name': 'Zara', 'Age': 7}; Variable Type : <class
of the passed print ("Variable Type : %s" % 'dict'>
A dictionary comprehension may hold more than one conditional statement (for of if
statements). In the above example, an ‘If statement’ may be added to filter out the desired
items to build a new dictionary.
Example 2:
even_squares={x : x **2 for x in range(10) if x%2 == 0}
print(even_squares)
Output :
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Example 3:
odd_squares={x : x **2 for x in range(10) if x%2 == 1}
print(odd_squares)
Output:
{1:1,3:9,5:25,7:49,9:81}
Example 2:
list = []
for letter in 'Apple':
list.append(letter)
print(list)
Output:
['A', 'p', 'p', 'l', 'e']
a) Using Conditionals With List Comprehensions
Example:
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = [fish for fish in fish_tuple if fish != 'octopus']
print(fish_list)
Output:
['blowfish', 'clownfish', 'catfish']
b) List comprehension using mathematical operators, integers, and the range() sequence
type.
Example:
number_list = [x ** 2 for x in range(10) if x % 2 == 0]
print(number_list)
Output
[0, 4, 16, 36, 64]
Program:
def ssort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
a=[]
n=int(input("Enter Upper Limit:"))
print("Enter the elements")
for i in range(n):
a.append(int(input()))
ssort(a)
print('After Sorting:',a)
Output
2. INSERTION SORT
Insertion sort is a simple sorting algorithm that works the way we sort playing cards
in our hands.
Program:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]
3. MERGESORT
In merge sort the unsorted list is divided into N sublists, each having one element,
because a list consisting of one element is always sorted.
Then, it repeatedly merges these sublists, to produce new sorted sublists, and in the
end, only one sorted list is produced.
Program:
myList = [12, 54, 3, 85, 73, 99, 37, 29]
def mergeSort(myList):
if len(myList)< 2: # if len(list) < 2, list already sorted
return myList
mid = int(len(myList)/2) # if len(list)>= 2 then divide list
x = mergeSort(myList[:mid]) # into two halves x= leftpart of myList
y = mergeSort(myList[mid:]) # and y = rightpart of myList
output = []
i=0
j=0
while i < len(x) and j < len(y):
if x[i] > y[j]:
output.append(y[j]) # sorting right part of myList
j += 1
else:
output.append(x[i]) # sorting left part of myList
i += 1
output += x[i:] # meging and sorting the myList
output += y[j:]
return output
print("The sorted list is: ", mergeSort(myList))
Output:
The sorted list is: [3, 12, 29, 37, 54, 73, 85, 99]
4. HISTOGRAM:
It is a statistical term for a collection of counters(or frequencies).
Program:
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
s=input()
print(histogram(s))
Output:
united
{'d': 1, 'e': 1, 'i': 1, 'n': 1, 't': 1, 'u': 1}