Lab 2 Manual
Lab 2 Manual
Lab 2 Manual
LAB # 02
LIST, TUPLE, DICTIONARY, CLASS AND OBJECT
OBJECTIVE
Familiarization with Python language using list, tuple, dictionary, class and object.
THEORY
A list is a collection of items in a particular order. You can make a list that includes the letters of
the alphabet, the digits from 0–9, or the names of all the people in your family. You can put
anything you want into a list, and the items in your list don’t have to be related in any particular
way. Because a list usually contains more than one element, it’s a good idea to make the name of
your list plural, such as letters, digits, or names.
It can have any number of items and they may be of different types (integer, float, string etc.). In
Python, square brackets ([]) indicate a list, and individual elements in the list are separated by
commas.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Some simple example of a list:
Example:
Output:
The simplest way to add a new element to a list is to append the item to the list. When you
append an item to a list, the new element is added to the end of the list. Using the same list we
had in the previous example, we’ll add the new element 'ducati' to the end of the list:
Example:
The append () method, adds 'ducati' to the end of the list without affecting any of the other
elements in the list:
Output:
Example#06:
Output:
The remove operation on a list is given a value to remove. It searches the list to find an
item with that value and deletes the first matching item it finds. It is an error if there is no
matching item.
The del statement can be used to delete an entire list. If you have a specific list item as
your argument to del. It is even possible to delete a "slice" from a list.
Organizing a List:
Python provides a number of different ways to organize your lists, depending on the situation.
Example#07:
Output:
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)
5 list(seq)
Converts a tuple into list.
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.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given
Tuples:
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. For example –
The block at line 1, defines the original tuple and prints the initial dimensions. At line 5, we store
a new tuple in the variable dimensions. We then print the new dimensions at line 6. Python
doesn’t raise any errors this time, because overwriting a variable is valid:
Output:
Dictionary:
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and
you can use a key to access the value associated with that key. A key’s value can be a number, a
string, a list, or even another 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. Dictionaries can store an almost limitless amount of information.
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.
Example:
Output:
Example:
Output:
Example:
The method items () returns a list of dict's (key, value) tuple pairs. The syntax of items ()
method is: dictionary.items ().
The key-value pairs are not returned in the order in which they were stored, even when
looping through a dictionary. Python doesn’t care about the order in which key-value
pairs are stored; it tracks only the connections between individual keys and their values.
Output:
Example:
Output:
>>> ob = Class()
This will create a new instance object named ob. We can access attributes of objects using the
object name prefix.
Attributes may be data or method. Method of an object are corresponding functions of that class.
Any function object that is a class attribute defines a method for objects of that class.
This means to say, since MyClass.func is a function object (attribute of class), ob.func will be a
method object.
Example:
Output:
Class Features:
Initialization (__init__):
The __init__ method is run as soon as an object of a class is instantiated. The method is useful to
do any initialization you want to do with your object. Notice the double underscore both in the
beginning and at the end in the name.
Example:
Output:
Lab#2 Exercise:
1. Store the names of a few of your friends in a list called names. Print each person’s name by
accessing each element in the list, one at a time.
2. If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list
that includes at least three people you’d like to invite to dinner. Then use your list to print a
message to each person, inviting them to dinner.
3. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you
need to send out a new set of invitations. You’ll have to think of someone else to invite.
Modify your list, replacing the name of the guest who can’t make it with the name
of the new person you are inviting.
Print a second set of invitation messages, one for each person who is still in your
list.
4. Implement graph using adjacency list using dictionary , make a class such as Vertex and
Graph then make some function such as add_nodes , add_edges, add_neighbors, add_vertex,
add_vertices and suppose whatever need it.
Home Assignment:
i) Implement Priority queue using heapq module.
ii) The lowest valued entries are retrieved first. A typical pattern for entries is a tuple in
the form: (priority_number, data) using queue module.
Using Pattern: (8,"low")
(1,"Very Imp")
(10,"Very low")
(5,"Normal")
(4,"Imp")