You are on page 1of 49

Unit 1:Chapter 2

List, Tuples and Dictionary


Lists

A list is a data type that can be used to store any type and number of variables and
information. Other important sequence types used in Python include lists. A sequence type is
formed by putting together some other types in a sequence. Here is how we form lists

You can define and assign items to a list with the expression:

my_list = [item_1, item_2, item_3]

Python also allows creation of an empty list:

my_list = []

To illustrate, let’s create a list of colors:

>>> colorlist=[‘Red’,’Green’,’blue’,’Yellow’,’Black’]

Let us create a number list

>>> numberlist=[1,2,3,4,5,6,7,8,9,10]

We can also create list with mix of elements

>>> mixlist=[1,2,'Hello','Class']

Another type of list can be declare that list is list in the list called nested list in this list we have a list
like number list[1,2,3,4,5] and if this number list has another list within the list is called nested list
Example
nestedlist=[1,2,[3,4,5,6],7,8,9,10]
This list is nested the element 3,4,5,6 are be accessed with the single subscript or address.
>>>print(nestedlist[2])
[3,3,4,5]

If you want to access the single element of the nested list then you have you give subscript
within the subscript
Example
>>>print(nestedlist[2][2])
5
In this example two subscript has given first subscript is for the outer list and second is for
inner list the nestedlist element 2 will first and then if element 2 is a list then the second
subscript element comes into the picture and the inner list has the access of 2nd element and
that element is 5.

Append()
You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append() method.

Syntax of append function

>>>list.append(item)

Example
colorlist.append(‘Voliet’)

append() can also be used to insert another list into the list

Example

>>>a=[1,2,3]

>>>b=[‘a’,’b’,’c’]

>>>a.append(b)

And the result of the append function is given below.

Append() will always insert item at the end like in the example give above violet color is
added in the list at the end of the list and also the list a is appended by list b so list b is
inserted at the end of list a.

Insert()

If you want to insert any item at a desired location so you have to use insert() method in
palace of append() method. Append() will always insert item at the end of list but with
insert() item will inserted at a particular place or index.

Syntax of insert function

>>>list.insert(index, item)

Example

Colorlist.insert(4,’White’)

Just like append() insert() can also be use to insert another list in the list.
As you have seen in the example given above that the white is inserted at the 4th index of
the list because list by default starts with 0 so index 4 is at the 5th place of the list. And the
vales of b list has inserted at the 1st index which is actually the 2nd place of the list

Remove()

To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.

Syntax of remove function is

>>>list.remove(item)

Example

>>>colorlist.remove(‘Yellow’)

In the above example yellow has removed from the list with remove(). We can use pop() and
del() functions for removing the elements from the list.pop and del is use to remove the
element by value but remove() is to remove with index.
Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string. In fact, lists respond to
all of the general sequence operations we used on strings in the prior chapter.

Python Expression Description


len(colorlist) It will calculate length of the list.
colorlost + numberlist It will concatenation of two lists.
[mixlist] * 4 It will repeat the values of the lists.
3 in [colorlist] It will inform you about whether the given value
is the member of the lists or not.
for x in numberlist: print x, It will give you the all values the list it will
automatically Iterate the position of the list.
Example

>>>len(colorlist)

because it start counting from 1 but the subscript of the list start with 0.

Example

>>>len(colorlist+numberlist)

15

Because colorlist has 5 and numberlist has 10 items so when both the lists are added.

If plus (+) operator used with numbers it add two numbers if we use it with list it used for
concatenation means joining two string or lists.

Example

>>>print(colorlist+numberlist)

[‘Red’,’Blue’,’White’,’Black’,’Yellow’,1,2,3,4,5,6,7,8,9,10]

As the multiplication is done with multiply (*) operator to the number similarly with the
list it can be repeated that much time which are given

Example

>>>print(numberlist * 2)

[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]
The will repeat itself two times because the multiplication is done by 2 if you multiply it
by 4it will repeat four times.

There is another function of list is seraching any element is the memer of the list or not it
just give you a true if the element is in the list else false.

Example

If we search 3 in the colorlist then the result will be false because colorlist have only the
names of the colors. But if we search 3 in the numberlist then the result will be true
because it contain 3 as a member of the list.

For showing iteration we need to have a loop let us take an example


The output of the iteration is

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings. You can also slice lists as you have access the values of the list with the subscript of
the list.

Example if you want to see a particular item of the list

>>>colorlist[0]

Red

Example

>>>print(colorlist[4])

Yellow
Example, if you only want to display the three colors from 2 to 5

>>>colorlist[2:5]

[‘Blue’,’Black’,’Yellow’]

it will display the 3rd 4th and 5th item of the list.

The list, tuple and string all works same with the subscripts, the first item is always starts
with 0 and the last item will be n-1 if the size of the list is n.

And there is negative representation of the subscript it always starts at the last item of the
list and the subscript starts with -1 and it move towards the first item of the list and decrease
subscript like -2,-3,-4 and so on.

Example

>>>print(colorlist[-1])

Black

because in case of negative subscript it starts from last element, colorlist has 5 elements and
it starts with

>>>print(colorlist[-4])

Green

Built-in List Functions & Methods


Python includes the following list functions
Sr.No. Function Description
1 len(list) Gives the total length of the list.
2 max(list) Returns item from the list with max
value.
3 min(list) Returns item from the list with min
value.
4 list(seq) Converts a tuple into list.
5 Sum(List) Add the all numeric values of the list.

Let us take an example to find the maximum, minimum and mean from a list.

In the above example an empty list has created and with help of the input function user
will enter the number of elements of the list. While loop will control the number of inputs
entered by the user and insert those values in the list with the append function. When
the list has completed then we are able to find the maximum minimum and average from
the list with the help built-in functions of list like max() and min() we can find it and for
average we have to use two built-in function sum() to find the sum of all the elements of
the list and with len() function we will find the number of elements of the list. With sum()
and len() we can easily find the average of the list.

The output of example:


Python includes following list methods
S.No. Methods Description
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.index(obj) Returns the lowest index in list that obj appears
4 list.insert(index, obj) Inserts object obj into list at offset index
5 list.pop(obj=list[-1]) Removes and returns last object or obj from list
6 list.remove(obj) Removes object obj from list
7 list.reverse() Reverses objects of list in place
8 list.sort(func) Sorts objects of list, use compare func if given
In the above example an empty list has created and with help of the input function user
will enter the number of elements of the list. For loop will control the number of inputs
entered by the user and insert those values in the list with the append() function. With
count() function we can count the number of occurrence of any elements in the list and
index() function gives us the lowest index of any number if that number occurs more than
one then it will return the lower index number of that number. As we have already
discussed insert() is use to insert value at any position in the list. For removing values
from the list we have two different function one is pop() and another is remove(). Pop() is
used to remove the value if the index is not known so list.pop(value) is used. If the you
want to remove value from the list with the help of index number so remove() function is
used list.remove(index). Reverse() function is use to reverse the elements of the list like
of list has elements 1,2,3,4,5 then after reverse() function list become 5,4,3,2,1 it will
reverse the elements of the list. Sort means arranging elements in ascending or
descending order so list.sort() function will give the list like 1,2,3,4,5 if the list is in
5,4,3,2,1 form.
Linear search using list

Linear search is a searing technique to search any element from the list. In this technique a
list is there with some elements and then user will enter a number for search in the listit will
check every element one by one linearly or sequentially. If the number found it will return
number found otherwise number not found.
Output of linear search is
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.

Its syntax is:

a=[[random.random() for row in range(number of row)]for col in range(number of column)]

Here random function is used. So we need to import random file.

Example

Write a program to input any matrix with mXn, and print the number on the output screen in
matrix format.

Matrix creation

Program 1
Output
There is another way to create matrix nested matrix without random function.

Program 2

A=[]

n=int(input("Enter N for N x N matrix : ")) #3 here

#use list for storing 2D array

#get the user input and store it in list (here IN : 1 to 9)

print("Enter the element ::>")

for i in range(n):

row=[] #temporary list to store the row

for j in range(n):

row.append(int(input())) #add the input to row list

A.append(row) #add the row to the list

print(A)

# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array

print("Display Array In Matrix Form")

for i in range(n):

for j in range(n):

print(A[i][j], end=" ") #new line

print()

B=[]

n=int(input("Enter N for N x N matrix : ")) #3 here

#use list for storing 2D array

#get the user input and store it in list (here IN : 1 to 9)

print("Enter the element ::>")

for i in range(n):
row=[] #temporary list to store the row

for j in range(n):

row.append(int(input())) #add the input to row list

B.append(row) #add the row to the list

print(B)

# [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

#Display the 2D array

print("Display Array In Matrix Form")

for i in range(n):

for j in range(n):

print(B[i][j], end=" ")

print() #new line

Output

>>> RESTART: C:/Users/Jayant Sharma/AppData/Local/Programs/Python/Python36/matrix


inout.py

Enter N for N x N matrix : 3

Enter the element ::>

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Display Array In Matrix Form

123

456

789

Enter N for N x N matrix : 3

Enter the element ::>

[[9, 8, 7], [6, 5, 4], [3, 2, 1]]

Display Array In Matrix Form

987

654

321

Matrix Addition

Write a program to input any two matrices and print sum of matrices.

Program 1

A=[]

n=int(input("Enter N for N x N matrix : ")) #3 here

#use list for storing 2D array


#get the user input and store it in list (here IN : 1 to 9)

print("Enter the element ::>")

for i in range(n):

row=[] #temporary list to store the row

for j in range(n):

row.append(int(input())) #add the input to row list

A.append(row) #add the row to the list

print(A)

# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array

print("Display Array In Matrix Form")

for i in range(n):

for j in range(n):

print(A[i][j], end=" ") #new line

print()

B=[]

n=int(input("Enter N for N x N matrix : ")) #3 here

#use list for storing 2D array

#get the user input and store it in list (here IN : 1 to 9)

print("Enter the element ::>")

for i in range(n):

row=[] #temporary list to store the row

for j in range(n):

row.append(int(input())) #add the input to row list

B.append(row) #add the row to the list

print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display the 2D array

print("Display Array In Matrix Form")

for i in range(n):

for j in range(n):

print(B[i][j], end=" ")

print() #new line

result = [[0,0,0], [0,0,0], [0,0,0]]

# iterate through rows

for i in range(n):

# iterate through columns

for j in range(len(A[0])):

result[i][j] = A[i][j] + B[i][j]

print("Resultant Matrix is ::>")

for r in result:

print("Resultant Matrix is ::>",r)

Output

>>>

RESTART: C:/Users/Jayant Sharma/AppData/Local/Programs/Python/Python36/matrix


inout.py

Enter N for N x N matrix : 3

Enter the element ::>

5
6

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Display Array In Matrix Form

123

456

789

Enter N for N x N matrix : 3

Enter the element ::>

[[9, 8, 7], [6, 5, 4], [3, 2, 1]]

Display Array In Matrix Form

987

654

321

Resultant Matrix is ::>


Resultant Matrix is ::> [10, 10, 10]

Resultant Matrix is ::> [10, 10, 10]

Resultant Matrix is ::> [10, 10, 10]

We can write addition of two matrix program with another method with random function

Program 2

Output
Matrix Multiplication

Write a program to input any two matrices and print product of matrices.
Output
Diagonals of a matrix

Write a program to input any matrix and print both diagonal values of the matrix.
Output
Tuple

A Tuple is a collection of Python objects separated by commas, or you can say a tuple is a
sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting
different comma-separated values. Optionally you can put these comma-separated values
between parentheses also.

Syntax of creating tuple

>>>tuplename=(element1,element2,….)

Example

Tuplecolor=(‘Red’,’Green’,’Blue’,’Yellow’,’Black’)

This is how we can create a string tuple, we can also create number tuple

Example

tuplenumber=(1,2,3,4,5,6,7,8,9,10)

A mix tuple mix means both the number and character are there in the list

Example

Tuplemix=(‘Hello’,’Class’,1,2,3)

If you want to declare an empty tuple you simply need to write parentheses “()” without any
value.

Example

Tupleempty=()
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. But you can create a new tuple with the existing tuples

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded. To explicitly remove
an entire tuple, just use the del statement.

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string. In fact, tuples respond
to all of the general sequence operations.
Python Expression Description
len(tuplenumber) It will calculate length of the tuple
(tuplecolor) + (tuplenumber) It will concatenation of two tuples
(tuplenew) * 2 It will repeat the values of the tuple
5 in (tuplenumber) It will inform you about whether the given
value is the member of the tuple or not
for x in tuplenumber: print x, It will give you the all values the tuple it will
automatically Iterate the position of the tuple

Example

>>>len(tuplenumber)

10

because it start counting from 1 but the subscript of the tuple start with 0.

Example

>>>len(tuplecolor+tuplenumber)

15

Because tuplecolor has 5 and tuplenumber has 10 items so when both the tuples are
added.

If plus (+) operator used with numbers it add two numbers if we use it with tuple it used
for concatenation means joining two string or tuples.

Example

>>>print(tuplecolor+tuplenumber)

[‘Red’,’Blue’,’White’,’Black’,’Yellow’,1,2,3,4,5,6,7,8,9,10]

As the multiplication is done with multiply (*) operator to the number similarly with the
list it can be repeated that much time which are given
Example

>>>print(numberlist * 2)

(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10)

The will repeat itself two times because the multiplication is done by 2 if you multiply it
by 4 it will repeat four times.

In expression is to use to find weather the given element is in the tuple or not.

For iteration we need to have a loop let us take an example

The output of the iteration is


Python includes the following tuple functions −

Sr.No. Function Description


1 len(tuple) Gives the total length of the tuple.
2 max(tuple) Returns item from the tuple with max value.
3 min(tuple) Returns item from the tuple with min value.
4 tuple(seq) Converts a list into tuple.

Output

In this example two tuple and a list has been created one tuple is color, one tuple is
number and a number list. print will show the list and tuple elements. Lenth efunction
will return the number of elements of the numbertuple. Max() will return the hignest
value in the tuple and tat is ‘Yellow’ because yellow has the highest ASCII value compared
to others elements of the tuple. And min() will return the minimum value of the tuple
that is ‘Black’ because first two character of ‘blue’ and ‘black’ are same but the third
charter of ‘black’ is ‘a’ and ‘blue’ is ‘u’ so ‘a’ has lower ASCII than ‘u’ so black will be
smallest element of the tuple. And tuple() will convert ant list into tuple as the
numberlist is list and with the help of tuple function it will converted into tuple

Example

Output

In the above example with the tuple function en empty tuple has created and then the
empty tuple is concatenated with the sting ‘PYTHON’ with plus(+) operator. The
statement t=t+(‘PYTHON’,) is use to concatenate and store the change in the tuple itself.
String ‘PYTHON’ is the single element of the tuple so the length of the tuple is 1 only.
Another tuple t1 has created with 3 elements because every element of the tuple is
seprated by comma, so t1 has three length.
Example

Let us take an example of swapping two tuples without using third tuple:

Output
Dictionary

A dictionary is like a list but instead of looking up an index to access values, you’ll be using a
unique key, which can be a number, string, or tuple. Dictionary values can be anything but
the keys must be an immutable data type. Each key is separated from its value by a colon
(:), the items are separated by commas, and the whole thing is enclosed in curly braces { }.
An empty dictionary without any items is written with just two curly braces, like this: {}.
Here is the syntax of dictionary structure: dictionary = {key_1 : a, key_2 : 2, key_3 : ab}

>>>ditem={“Tea”:10,”Coffee”:20,”,”Cold Drink”:35,”Mango Shake”:50}

Accessing Values in Dictionary


A dictionary can be a very useful tool for storing and manipulating key-value pairs such as
those used in phone books, dictionary, menu, or log-in data.
>>>print(ditem)
{“Tea”:10,”Coffee”:20,”,”Cold Drink”:35,”Mango Shake”:50}
To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value.
>>>print(“Ditem[Tea]”,ditem[“Tea”])
Ditem[Tea] 10
By this we can access ant item from dictionary the value in the double coats is just to display
the what value it contain and after comma(,) ditem is the name of dictionary and tea is the
item for which user wants the associated value.
To see how dictionaries actually work, you can create a dictionary named ditem with item
and prices pairs. If we attempt to access a data item with a key, which is not part of the
dictionary, we get an error.

Let us take an example of taking input from the use and store them in the dictionary and then
use it to get desired output.
Output

We have created a empty dictionary with the function dict() naming menu and user will enter
the number of elements of the dictionary. With the help of while loop user will enter the
name of the item in the menu and the price of that item. And that will store in the
dictionary. Then with the help of for loop we can access the elements of the dictionary.

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry. The syntax of adding any item is: dictionary [“new key”
]= Value like
>>>ditem[“Cold Coffee”]=50.
You might want to change the values in any of the keys at one point. For instance, you need
to change the price of “Cold Drink” from 35 to 45. The Syntex for updating any value
dictionary [“Existing key”]= Value like
>>>ditem[“Cold Drink”] = 45
Delete Dictionary Elements

Assuming you no longer want to include spam in your menu, you can easily do so with the del
method. Syntax is del dictionary[‘item’].If you want to remove all entries in the dictionary,
you can use the method dictionary.clear().To clear all entries in the menu:

>>>ditem.clear(menu)

The Python Shell displayed an empty dictionary with the clear command. Now that it contains
no data at all, you might decide to delete the dictionary. You can do so with the del method:
del dictionary.

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −
S.No. Function Description
1 len(dictionary) Gives the total length of the dictionary. This would be equal to
the number of items in the dictionary.
2 str(dictionary) Produces a printable string representation of a dictionary
3 type(variable) Returns the type of the passed variable. If passed variable is
dictionary, then it would return a dictionary type.

Python includes following dictionary methods −


Sr.No. Methods with Description
1 dictionary.clear() Removes all elements of dictionary
2 dictionary.copy() Returns a shallow copy of dictionary
3 dictionary.get(key, default=None) For key key, returns value or default if key not
in dictionary
4 dictionary.items() Returns a list of dictionary‘s (key, value) tuple
pairs
5 dictionary.keys() Returns list of dictionary dictionary's keys
6 dictionary.update(dictionary 2) Adds dictionary dictionary 2's key-values pairs
to dictionary
7 dictionary.values() Returns list of dictionary dictionary’s values

Here is the uses of the above given methods of dictionary.

Copy() function creates the copy of ditem dictionary. Item() function shows the all the
item of the in the dictionary. Keys() function will only show the keys of the dictionary.
Just like keys() values() function is also use to show only the values associated with
different keys of the dictionary
Sorting algorithm

Sorting is any process of arranging items systematically, and has two common, yet distinct
meanings: ordering: arranging items in a sequence ordered by some criterion; categorizing:
grouping items with similar properties.

we can distinguish two types of sorting. If the number of objects is small enough to fits into
the main memory, sorting is called internal sorting. If the number of objects is so large that
some of them reside on external storage during the sort, it is called external sorting.

In this chapter we consider the following internal sorting algorithms

Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in
form of an list with n number of elements. Bubble Sort compares all the element one by one
and sort them based on their values.

If the given array has to be sorted in ascending order, then bubble sort will start by
comparing the first element of the array with the second element, if the first element is
greater than the second element, it will swap both the elements, and then move on to
compare the second and the third element, and so on.

If we have total n elements, then we need to repeat this process for n-1 times.

It is known as bubble sort, because with every complete iteration the largest element in the
given array, bubbles up towards the last place or the highest index, just like a water bubble
rises up to the water surface.

Sorting takes place by stepping through all the elements one-by-one and comparing it with
the adjacent element and swapping them if required.

Implementing Bubble Sort Algorithm

Following are the steps involved in bubble sort(for sorting a given array in ascending order):

 Starting with the first element(index = 0), compare the current element with the next
element of the array.
 If the current element is greater than the next element of the array, swap them.
 If the current element is less than the next element, move to the next
element. Repeat Step 1.

Example:
First Pass:

( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap
since 5 > 2.( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 >
5), algorithm does not swap them.
Second Pass:

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 ( 1 2 4 5 8 ) –> ( 1


2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) Now, the array is already sorted, but our algorithm does
not know if it is completed. The algorithm needs one whole pass without any swap to know it
is sorted.

Third Pass:

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )


( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Insertion sort
Insertion sort is based on the idea that one element from the input elements is consumed in
each iteration to find its correct position i.e, the position to which it belongs in a sorted
array.

It iterates the input elements by growing the sorted array at each iteration. It compares the
current element with the largest value in the sorted array. If the current element is greater,
then it leaves the element in its place and moves on to the next element else it finds its
correct position in the sorted array and moves it to that position. This is done by shifting all
the elements, which are larger than the current element, in the sorted array to one position
ahead

Implementing Insertion Sort Algorithm

 The second element of an array is compared with the element that appears before it
(only first element in this case). If the second element is smaller than first element,
second element is inserted in the position of first element. After first step, first two
elements of an array will be sorted.
 The third element of an array is compared with the element that appears before it
(first and second element). If third element is smaller than first element, it is inserted
in the position of first element. If third element is larger than first element but,
smaller than second element, it is inserted in the position of second element. If third
element is larger than both the elements, it is kept in the position as it is. After
second step, first three elements of an array will be sorted.
 Similarly, the fourth element of an array is compared with the elements that appears
before it (first, second and third element) and the same procedure is applied and that
element is inserted in the proper position. After third step, first four elements of an
array will be sorted.

Example

12, 11, 13, 5, 6

Let us loop for i = 1 (second element of the array) to 5 (Size of input array)

i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12, 11, 12, 13, 5, 6.

i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13,11,
12,13,5,6.

i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one
position ahead of their current position 5, 11, 12, 13, 6.

i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position
ahead of their current position 5, 6, 11, 12, 13
Summery

 A list is a data type that can be used to store any type and number of variables and
information, it is editable in nature.
 List can update be by using append()and insert()method.
 List items can be removed by remove() and del method.
 List have different functions like len(), concatenate( + ),repetition( * ), membership,
iteration, min(), max(), cmp(), list().
 A Tuple is a collection of Python objects which is immutable in nature.
 Tuples cannot be updated they only be deleted using del method.
 Like list tuple have different function len(), concatenate( + ),repetition( * ),
membership, iteration, min(), max(), cmp(), list().
 A dictionary is like a list but instead of looking up an index to access values, you’ll be
using a unique key, which can be a number, string, or tuple.
 Like lists dictionary can be updated new values can be added and existing values can
be updated.
 Dictionary values can be removed using remove and del method.
 Del method can be use to remove the entire dictionary and single value can c=be
removed by del method itself.
 Like list and tuples dictionary have may function like len(), cmp(),str() and type().
 Sorting is any process of arranging items systematically

Multiple Choice Questions

Q.1 What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?

A - [ 'abcd', 786 , 2.23, 'john', 70.2 ]

B - abcd

C - [786, 2.23]

D - [2.23, 'john', 70.2]

Answer : D

Explanation

It will print elements starting from 3rd element. Output would be [2.23, 'john', 70.2].

Q.2 What is the output of ['Hi!'] * 4?

A - ['Hi!', 'Hi!', 'Hi!', 'Hi!']

B - ['Hi!'] * 4

C - Error

D - None of the above.

Answer : A

Explanation

['Hi!', 'Hi!', 'Hi!', 'Hi!']


Q.3 What is the following function compares elements of both dictionaries dict1, dict2?

A - max(dict)

B - min(dict)

C - len(dict)

D - None of the above.

Answer : C

Explanation

len(dict) − Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.

Q.4 Which of the following commands will create a list?

a) list1 = list()
b) list1 = [].
c) list1 = list([1, 2, 3])
d) all of the mentioned
Answer: d
Explanation: Execute in the shell to verify

Q.5 What is the output when we execute list(“hello”)?


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’].
b) [‘hello’].
c) [‘llo’].
d) [‘olleh’].
Answer: a
Explanation: Execute in the shell to verify.

Q.6 Suppose listExample is [‘h’,’e’,’l’,’l’,’o’], what is len(listExample)?


a) 5
b) 4
c) None
d) Error
Answer: a
Explanation: Execute in the shell and verify.

Q.7 Suppose list1 is [2445,133,12454,123], what is max(list1) ?


a) 2445
b) 133
c) 12454
d) 123
Answer: c
Explanation: Max returns the maximum element in the list.

Q.8 Suppose list1 is [3, 5, 25, 1, 3], what is min(list1) ?


a) 3
b) 5
c) 25
d) 1
Answer: d
Explanation: Min returns the minimum element in the list.

Q.9 Which of the following is a Python tuple?


a) [1, 2, 3].
b) (1, 2, 3)
c) {1, 2, 3}
d) {}
View Answer

Answer: b
Explanation: Tuples are represented with round brackets.

Q.10 Suppose t = (1, 2, 4, 3), which of the following is incorrect?


a) print(t[3])
b) t[3] = 45
c) print(max(t))
d) print(len(t))
Answer: b
Explanation: Values cannot be modified in the case of tuple, that is, tuple is immutable.

Q.11 What will be the output?

>>>t=(1,2,4,3)

>>>t[1:3]

a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)
Answer: c
Explanation: Slicing in tuples takes place just as it does in strings.

Q.12 What will be the output?

>>>t = (1, 2, 4, 3, 8, 9)

>>>[t[i] for i in range(0, len(t), 2)]


a) [2, 3, 9].
b) [1, 2, 4, 3, 8, 9].
c) [1, 4, 8].
d) (1, 4, 8)
Answer: c
Explanation: Execute in the shell to verify.

Q.13 What will be the output?

d = {"john":40, "peter":45}

d["john"]

a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.

Q.14 What will be the output?

>>>t = (1, 2)

>>>2 * t

a) (1, 2, 1, 2)
b) [1, 2, 1, 2].
c) (1, 1, 2, 2)
d) [1, 1, 2, 2].
Answer: a
Explanation: * operator concatenates tuple.

Q.15 Read the code shown below carefully and pick out the keys?

d = {"john":40, "peter":45}

a) “john”, 40, 45, and “peter”


b) “john” and “peter”
c) 40 and 45
d) d = (40:”john”, 45:”peter”)
Answer: b
Explanation: Dictionaries appear in the form of keys and values.

Q.16 What will be the output?

d = {"john":40, "peter":45}
"john" in d

a) True
b) False
c) None
d) Error
Answer: a
Explanation: In can be used to check if the key is int dictionary.

Q.17 What will be the output?

d1 = {"john":40, "peter":45}

d2 = {"john":466, "peter":45}

d1 == d2

a) True
b) False
c) None
d) Error

Answer:b
Q.18 What will be the output?

d1 = {"john":40, "peter":45}

d2 = {"john":466, "peter":45}

d1 > d2

a) True
b) False
c) Error
d) None
Answer: c
Explanation: Arithmetic > operator cannot be used with dictionaries.

Q.19 What is the output?

d = {"john":40, "peter":45}

d["john"]

a) 40
b) 45
c) “john”
d) “peter”
Answer: a
Explanation: Execute in the shell to verify.

Q.20 Suppose d = {“john”:40, “peter”:45}. To obtain the number of entries in dictionary


which command do we use?
a) d.size()
b) len(d)
c) size(d)
d) d.len()
Answer: b
Explanation: Execute in the shell to verify.

Practice Questions

Q.1 What are Python's dictionaries?

Q.2 What are Python’s list?

Q.3 What are Python’s tuple?

Q.4 What are the key differences of list, tuple, and dictionary?

Q.5 Is it possible to change the values of tuple and list ? Give explanation with example.

Q.6 How the values of the dictionary can be removed?

Q.7 What is sorting algorithm? What is the difference between bubble sort and insertion sort.

Laboratory Questions

Q.1 Write a program to find the duplicate values in the list.

Q.2 Write a program to find the compare two list are equal or not.

Q.3 Write a program to find generates a reverse list with and without built-in functions.

Q.4 Write a program to find the frequency of the elements of the list.

Q.5 Write a program to find sum and product of all the list elements.

Q.6 Write a program to find smallest number in the list without using min function.

Q.7 Write a program to find largest number in the list without using max function.

Q.8 Write a program to find weather the list is empty or not.

Q.9 Write a program to generate and print a dictionary that contains a number (between 1
and n) in the form (x, x*x). Sample Dictionary (n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4:
16, 5: 25}
Q.10 Write a program to convert a tuple to a string.

You might also like