GE8151 Unit IV
GE8151 Unit IV
4.1 Lists
A list is a sequence of values. In a string, the values are characters; in a list, they can be
any type. The values in a list are called elements or sometimes items. There are several ways to
create a new list; the simplest is to enclose the elements in square brackets ([ and ]):
The elements of a list don‟t have to be the same type. The following list contains a string,
a float, an integer, and another list:
['spam', 2.0, 5, [10, 20]]
A list within another list is called nested list. A list that contains no elements is called an
empty list; we can create one with empty brackets, [].
We can assign list values to variables:
Indexing:
An element in the list can be accessed through index operator.
Syntax:
list_name[index] Mr. P. J. Merbin Jose
2
Python allows negative indexing to access the elements. Index -1 refers the last element on the
list, -2 refers the second last element and so on.
Slicing:
List slice is same of string slice. From the list slice we can extract sub part of list based
on user requirements. We can use index values to create a sub list from list.
Syntax:
Var_name=list_name[start value: end value: increment/ decrement step value]
Here start value and end value may be omitted or optional. Default value for start is zero. Default
value for last is last index or -1. Default step value is 1.
Concatenation:
To concatenate or combine two or more lists “+” operator is used.
Repetitions:
Lists can be repeated or repeatedly concatenated with the asterisk operator “*”. The *
operator repeats a list in given number of times.
Membership:
We can determine whether an element is present in the list by using in or not in
operator. The in operator returns true if particular element is present, else it returns false. The
not in operator returns true if particular element is not present, else it returns false.
Here total is initialized to 0. Each time through the loop, x gets one element from the list. The +=
operator provides a short way to update a variable. This augmented assignment statement,
total += x
is equivalent to
total = total + x
As the loop runs, total accumulates the sum of the elements; a variable used this way is
sometimes called an accumulator.
Filter - select some of the elements from a list and return a sublist
Example: Function takes a list of strings and returns a list that contains only the uppercase
strings:
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
Here „isupper‟ is a string method that returns True if the string contains only upper case letters.
An operation like only_upper is called a filter because it selects some of the elements and filters
out the others.
Deleting elements
There are several ways to delete elements from a list.
If we know the index of the element, we can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> t
['a', 'c']
>>> x
'b'
pop modifies the list and returns the element that was removed.
If an index is not given, it deletes and returns the last element.
If we don‟t need the removed value, we can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
['a', 'c']
If you know the element we want to remove (but not the index), we can use remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> t
['a', 'c']
The return value from remove is None.
To remove more than one element, we can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
['a', 'f']
As usual, the slice selects all the elements up to but not including the second index.
5
4.1.2 List slices
List slicing is an operation that extracts a subset of elements from a list and packages
them as another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
If we omit the first index, the slice starts at the beginning. If we omit the second, the slice goes to
the end. So if we omit both, the slice is a copy of the whole list. i.e [:] this will print the entire list
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
[2:2] this will create an empty slice.
>>> a[2:2]
[]
>>> a=[9,8,7,6,5,4]
>>> a[0:6:2]
[9, 7, 5]
>>> a[0:6:3]
[9,6]
Since lists are mutable, it is often useful to make a copy before performing operations that
modify lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', 'f']
Syntax
Listname.methodname(element/index/list)
Split:
If we want to break a string into words, we can use the split method:
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> t
['pining', 'for', 'the', 'fjords']
An optional argument called a delimiter specifies which characters to use as word boundaries.
The following example uses a hyphen as a delimiter:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> t = s.split(delimiter)
>>> t
['spam', 'spam', 'spam']
Join
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string
method, so we have to invoke it on the delimiter and pass the list as a parameter:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> s = delimiter.join(t)
>>> s
'pining for the fjords'
In this case the delimiter is a space character, so join puts a space between words. To concatenate
strings without spaces, we can use the empty string, '', as a delimiter.
Traversing a list
List using for loop:
The most common way to traverse the elements of a list is with a „for‟ loop.
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
Iterating over a sequence is called traversal.
Loop continues until we reach the last item in the sequence.
8
Syntax
for <item> in <iterable>:
<body>
Eg:
>>>names = ["Neha","John","Mary","Janice","Johan"]
>>>for name in names:
...print("Hi "+ name +"!")
This loop traverses the list and updates each element. len returns the number of elements
in the list. range returns a list of indices from 0 to n - 1, where n is the length of the list. Each
time through the loop i gets the index of the next element. The assignment statement in the body
uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never runs the body:
for x in []:
print('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length
of this list is four: ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
Output: 15
4.1.5 Mutability:
Lists are mutable. (can be changed)
Mutability is the ability for certain types of data to be changed without entirely recreating
it.
An item can be changed in a list by accessing it directly as part of the assignment
statement.
Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list items can be updated.
The syntax for accessing the elements of a list is the same as for accessing the characters
of a string—the bracket operator. The expression inside the brackets specifies the index.
Remember that the indices start at 0:
>>> cheeses[0]
'Cheddar'
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.
>>> numbers = [42, 123]
>>> numbers[1] = 5
>>> numbers
[42, 5]
Figure below shows the state diagram for cheeses, numbers and empty:
Example Description
>>> a=[1,2,3,4,5] changing single element
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
>>> a=[1,2,3,4,5] changing multiple element
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
>>> a=[1,2,3,4,5] The elements from a list can
>>> a[0:3]=[ ] also be removed by assigning
>>> print(a) the empty list to them.
[4, 5]
>>> a=[1,2,3,4,5] The elements can be inserted
>>>a[0:0]=[20,30,45] into a list by squeezing them
>>> print(a) into an empty slice at the
[20,30,45,1, 2, 3, 4, 5] desired location.
In this case we would say that the two lists are equivalent, because they have the same
elements, but not identical, because they are not the same object. If two objects are identical,
they are also equivalent, but if they are equivalent, they are not necessarily identical.
4.1.6 Aliasing
Creating a copy of a list is called aliasing. When we create a copy both list will be having
same memory location. Changes in one list will affect another list. Aliasing refers to having
different names for same list values.
If a refers to an object and we assign b = a, then both variables refer to the same object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
The state diagram looks like,
The association of a variable with an object is called a reference. In this example, there
are two references to the same object. An object with more than one reference has more than one
name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other. When the
first element of the list named “a” is replaced, the first element of the list named “b” is also
replaced.
>>> b[0] = 42
>>> a
[42, 2, 3]
This type of change is known as a side effect. This happens because after the assignment
b=a, the variables a and b refer to the exact same list object. They are aliases for the same object.
This phenomenon is known as aliasing. To prevent aliasing, a new object can be created and the
contents of the original can be copied which is called cloning.
In python, arguments are passed by reference. When we pass a list to a function, the
function gets a reference to the list. If the function modifies the list, the caller sees the change. If
any changes are done in the parameter which refers within the function, then the changes also
reflects back in the calling function.
Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change the
same list that the argument is referencing.
For example, delete_head removes the first element from a list:
def delete_head(t):
del t[0]
It is important to distinguish between operations that modify lists and operations that create new
lists. For example, the append method modifies a list, but the + operator creates a new list.
The result of the operator is a new list, and the original list is unchanged.
For example, this function does not delete the head of a list:
def bad_delete_head(t):
t = t[1:]
The slice operator creates a new list and the assignment makes t refer to it, but that doesn‟t affect
the caller.
>>> t4 = [1, 2, 3]
>>> bad_delete_head(t4)
>>> t4
[1, 2, 3]
At the beginning of bad_delete_head, t and t4 refer to the same list. At the end, t refers to a new
list, but t4 still refers to the original, unmodified list.
An alternative is to write a function that creates and returns a new list. For example, tail returns
all from the first element of a list:
def tail(t):
return t[1:]
This function leaves the original list unmodified. Here‟s how it is used:
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> rest
['b', 'c']
14
Example 1: Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Example 2: Output
def insidefun(a): inside [11, 12, 13, 14, 15]
for i in range(0,len(a),1): outside [11, 12, 13, 14, 15]
a[i]=a[i]+10
print(“inside”,a)
a=[1,2,3,4,5]
insidefun(a)
print(“outside”,a)
Example 3: Output
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
4.2 TUPLES
Another way to create a tuple is the built-in function tuple. With no argument, it creates an
empty tuple:
>>> t = tuple()
>>> print t
()
15
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the
sequence:
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, we should avoid using it as a variable
name. Most list operators also work on tuples. The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
But if we try to modify one of the elements of the tuple, we get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
we can‟t modify the elements of a tuple, but we can replace one tuple with another:
>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')
Benefits of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
The return value from split is a list with two elements; the first element is assigned to
uname, the second to domain
>>> print uname
monty
>>> print domain
python.org
max and min are built-in functions that find the largest and smallest elements of a sequence.
min_max computes both and returns a tuple of two values.
Example1: Output:
def div(a,b): enter a value:4
r=a%b enter b value:3
q=a//b reminder: 1
return(r,q) quotient: 1
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
17
Example2: Output:
def min_max(a): smallest: 1
small=min(a) biggest: 6
big=max(a)
return(small,big)
a=[1,2,3,4,6]
small,big=min_max(a)
print("smallest:",small)
print("biggest:",big)
The gather parameter can have any name we like, but args is conventional. Here‟s how the
function works:
>>> printall(1, 2.0, '3')
(1, 2.0, '3')
The complement of gather is scatter. If we have a sequence of values and we want to
pass it to a function as multiple arguments, we can use the * operator. For example, divmod takes
exactly two arguments; it doesn‟t work with a tuple:
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
The result is a list of tuples where each tuple contains a character from the string and the
corresponding element from the list.
If the sequences are not the same length, the result has the length of the shorter one.
>>> zip('Anne', 'Elk') [('A', 'E'), ('n', 'l'), ('n', 'k')]
Each time through the loop, Python selects the next tuple in the list and assigns the elements to
letter and number. The output of this loop is:
0a
1b
19
2c
If we combine zip, for and tuple assignment, we get a useful idiom for traversing two (or
more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and
returns True if there is an index i such that t1[i] == t2[i]:
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
If we need to traverse the elements of a sequence and their indices, we can use the built-in
function enumerate:
for index, element in enumerate('abc'):
print index, element
The dictionary method update also takes a list of tuples and adds them, as key-value
pairs, to an existing dictionary. Combining items, tuple assignment and for, we get the idiom for
traversing the keys and values of a dictionary:
for key, val in d.items():
print val, key
The output of this loop is:
20
0a
2c
1b
It is common to use tuples as keys in dictionaries (primarily because we can‟t use lists).
For example, a telephone directory might map from last-name, first-name pairs to telephone
numbers. Assuming that we have defined last, first and number, we could write:
directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment to traverse this
dictionary.
This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple
to last and first, then prints the name and corresponding telephone number. There are two ways
to represent tuples in a state diagram. The more detailed version shows the indices and elements
just as they appear in a list.
Comparing tuples
The relational operators work with tuples and other sequences; Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the next
elements, and so on, until it finds elements that differ. Subsequent elements are not considered
(even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
The sort function works the same way. It sorts primarily by first element, but in the case
of a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU for
Decorate a sequence by building a list of tuples with one or more sort keys preceding the
elements from the sequence, Sort the list of tuples, and Undecorate by extracting the sorted
elements of the sequence.
For example, suppose you have a list of words and you want to sort them from longest to
shortest:
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
21
for length, word in t:
res.append(word)
return res
The first loop builds a list of tuples, where each tuple is a word preceded by its length.
sort compares the first element, length, first, and only considers the second element to break ties.
The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order of
length.
Tuple Methods
Methods Example Description
a.index(tuple) >>> a=(1,2,3,4,5) Returns the index of the
>>> a.index(5) first matched item.
4
a.count(tuple) >>>a=(1,2,3,4,5) Returns the count of the
>>> a.count(3) given element.
1
len(tuple) >>> len(a) return the length of the
5 Tuple
min(tuple) >>>min(a) return the minimum element
1 in a Tuple
max(tuple) >>>max (a) return the maximum element
5 in a Tuple
del(tuple) >>>del (a) Delete the entire tuple
4.3 DICTIONARY
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
4.3.1 Operations
How to create a dictionary?
Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.
An item has a key and the corresponding value expressed as a pair, key: value. While
values can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
We can also create a dictionary using the built-in function dict().
# using dict()
22
my_dict = dict({1:'apple', 2:'ball'})
How to access elements from a dictionary?
While indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is
not found.
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
OUTPUT: Jack
26
# Trying to access keys which doesn't exist throws error
>>>my_dict.get('address')
>>>my_dict['address']
#Error:
Example:
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
list(sorted(marks.keys()))
Output:
25
{'English': 0, 'Math': 0, 'Science': 0}
('English', 0)
('Math', 0)
('Science', 0)
['English', 'Math', 'Science']
Function Description
all() Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary
is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries.
sorted() Return a new sorted list of keys in the dictionary.
Here are some examples that uses built-in functions to work with dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(len(squares))
print(sorted(squares))
Output:
5
[1, 3, 5, 7, 9]
Difference between List, Tuples and dictionary:
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)]
print(pow2)
Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
This code is equivalent to
pow2 = []
for x in range(10):
pow2.append(2 ** x)
A list comprehension can optionally contain more for or if statements. An optional if statement
can filter out items for the new list.
Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']] ['Python
Language', 'Python Programming', 'C Language', 'C Programming']
27
List Comprehension Output
>>>L=[x**2 for x in range(0,5)] [0, 1, 4, 9, 16]
>>>print(L)
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2] [1, 4, 9]
>>> [x**2 for x in mixed if type(x)==int]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]
>>> num=[-1,2,-3,4,-5,6,-7] [2, 4, 6]
>>> [x for x in num if x>=0]
>>> str=["this","is","an","example"] ['t', 'i', 'a', 'e']
>>> element=[word[0] for word in str]
>>> print(element)
Programs on matrix:
Matrix addition Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
c[i][j]=a[i][j]+b[i][j]
for i in c:
print(i)
Matrix multiplication Output
a=[[1,1],[1,1]] [3, 3]
b=[[2,2],[2,2]] [3, 3]
c=[[0,0],[0,0]]
for i in range(len(a)):
for j in range(len(b)):
for k in range(len(b)):
c[i][j]=a[i][j]+a[i][k]*b[k][j]
for i in c:
print(i)
Matrix transpose Output
a=[[1,3],[1,2]] [1, 1]
c=[[0,0],[0,0]] [3, 2]
for i in range(len(a)):
for j in range(len(a)):
c[i][j]=a[j][i]
for i in c:
print(i)
28
4.5 ILLUSTRATIVE PROGRAM
becomes
with each element greater than x copied to the right as it is compared against x.
alist = []
print('Insertion Sort :')
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
alist.append(x)
insertionSort(alist)
print(alist)
Output:
#For example alist = [54,26,93,17,77,31,44,55,20]
[17, 20, 26, 31, 44, 54, 55, 77, 93]
30
Example
The following figure shows the fifth pass in detail. At this point in the algorithm, a sorted sublist
of five items consisting of 17, 26, 54, 77, and 93 exists. We want to insert 31 back into the
already sorted items. The first comparison against 93 causes 93 to be shifted to the right. 77 and
54 are also shifted. When the item 26 is encountered, the shifting process stops and 31 is placed
in the open position. Now we have a sorted sublist of six items.
The following figure shows how the list as it is being sorted by merge sort.
Splitting
32
Merging
Output:
**
***
******
*****
Additional programs:
1. Python program to find the factorial of a number.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
9. Program to sort alphabetically the words from a string provided by the user
import calendar
y=int(input("enter year:"))
m=int(input("enter month:"))
print(calendar.month(y,m))
Question bank
PART – A
1. What is slicing?
2. How can we distinguish between tuples and lists?
3. What will be the output of the given code?
a. List=[„p‟,‟r‟,‟i‟,‟n‟,‟t‟,]
b. print List[2:]
4. Give the syntax required to convert an integer number into string?
5. List is mutable. Justify?
6. Difference between del and remove methods in List?
7. Difference between pop and remove in list?
8. How are the values in a tuple accessed?
9. What is a Dictionary in Python?
10. Define list comprehension.
11. Write a python program using list looping.
12. What do you meant by mutability and immutability?
13. Define Histogram.
14. Define Tuple and show it is immutable with an example.
15. State the difference between aliasing and cloning in list
16. What is list cloning?
17. What is deep cloning?
Mr. P. J. Merbin Jose
36
18. State the difference between pop and remove method in list.
19. Create tuple with single element.
20. Swap two numbers without using third variable.
21. Define properties of key in dictionary.
22. How can you access elements from the dictionary?
23. Difference between delete and clear method in dictionary.
24. What is squeezing in list? Give an example.
25. How to convert a tuple in to list?
26. How to convert a list in to tuple?
27. Create a list using list comprehension.
28. Advantage of list comprehension.
29. What is the use of map () function?
30. How can you return multiple values from function?
31. What is sorting and types of sorting?
32. Find length of sequence without using library function.
33. How to pass tuple as argument?
34. How to pass a list as argument?
35. What is parameter and types of parameter?
36. How can you insert values in to dictionary?
37. What is key value pair?
38. Mention different data types can be used in key and value.
39. What are the immutable data types available in python?
40. What is the use of fromkeys() in dictioanary?
PART-B
1. Explain in details about list methods.
2. Discuss about operations in list.
3. What is cloning? Explain it with example.
4. What is aliasing? Explain with example.
5. How can you pass list into function? Explain with example.
6. Explain tuples as return values with examples.
7. Write a program for matrix multiplication.
8. Write a program for matrix addition.
9. Write a program for matrix subtraction.
10. Write a program for matrix transpose.
11. Write procedure for selection sort.
12. Explain merge sort with an example.
13. Explain insertion with example.
14. Explain in detail about dictionaries and its methods.
15. Explain in detail about advanced list processing