Unit-Ii Python Data Structures, Packages
Unit-Ii Python Data Structures, Packages
Lists :
• A list is an ordered set of values, where each value is identified by an index.
• The values that make up a list are called its elements .
• Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type.
• Lists and strings—and other things that behave like ordered sets—are
called sequences .
• The list is the most versatile datatype available in Python, which can be
written as a list of comma-separated values (items) between square
brackets.
• Important thing about a list is that the items in a list need not be of the
same type.
• There are several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ]):
• [10, 20, 30, 40] ["spam", "bungee", "swallow"]
• A list within another list is said to be nested .
• It is called the empty list, and is denoted []. Like numeric 0 values and the empty
string, the empty list is false in a boolean expression:
-------------------------------------------------------------------------------------------------
• The values stored in a list can be accessed using the slice operator ([ ] and
[:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1.
• The plus (+) sign is the list concatenation operator, and the asterisk (*) is
the repetition operator.
list = [ 'abcd', 786 , 2.23, 'john',
70.2 ]
tinylist = [123, 'john']
# Prints complete list
print (list)
# Prints first element of the list
print (list[0])
# Prints elements starting from 2nd till 3rd
print (list[1:3])
# Prints elements starting from 3rd element
print (list[2:])
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
Lists are mutable :
• Unlike strings lists are mutable , which means we can change their elements.
• Using the bracket operator on the left side of an assignment, we can update one of
the elements:
• >>> fruit = ["banana", "apple", "quince"]
• >>> fruit[0] = "pear"
• >>> fruit[-1] = "orange"
• >>> print fruit
• [’pear’, ’apple’, ’orange’]
Explanation:
• The bracket operator applied to a list can appear anywhere in an expression. When it
appears on the left side of an assignment, it changes one of the elements in the list,
so the first element of fruit has been changed from "banana" to "pear", and the last
from "quince" to "orange".
• An assignment to an element of a list is called item assignment.
Item assignment does not work for strings:
>>> my_string = "TEST"
>>> my_string[2] = "X"
Traceback (most recent call last): File "<stdin>", line 1, in
<module>
TypeError: ’str’ object does not support item assignment
--------------------------------------------------------------------------------------------------------
-------------------------
but it does for lists:
>>> my_list = ["T", "E", "S", "T"]
>>> my_list[2] = "X"
>>> my_list
[’T’, ’E’, ’X’, ’T’]
• With the slice operator we can update several
elements at once:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3] = ["x", "y"]
>>> print a_list
[’a’, ’x’, ’y’, ’d’, ’e’, ’f’]
• 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.
Built-in List functions and methods :
• Python includes the following list functions :
Listlen()Method
Description
• The len() method returns the number of elements in the list.
Syntax
Following is the syntax for len() method-
len(list)
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example
list1 = ['physics', 'chemistry', 'maths']
print (len(list1))
list2=list(range(5)) #creates list of numbers between 0-4 print (len(list2)) shows the usage of
len() method.
List max() Method :
Description
The max() method returns the elements from the list with maximum value.
Syntax
• Following is the syntax for max() method-
max(list)
Parameters
list - This is a list from which max valued element are to be returned.
Return Value
This method returns t
Example
The following example shows the usage of max() method.
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
List min() Method :
Description
• The method min() returns the elements from the list with minimum value.
Syntax
Following is the syntax for min() method-
min(list)
Parameters
list - This is a list from which min valued element is to be returned.
Return Value
• This method returns the elements from the list with minimum value.
Example :
list1 = ['physics', 'Biology', 'chemistry', 'maths'] list1.remove('Biology')
print ("list now : ", list1) list1.remove('maths')
print ("list now : ", list1)
list now :
['physics', 'chemistry', 'maths']
['physics', 'chemistry']
Listreverse()Method
Description
• The reverse() method reverses objects of list in place.
Syntax
Following is the syntax for reverse() method-
list.reverse()
Parameters
• NA
Return Value
• This method does not return any value but reverse the given object from the list. \
• To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain the value available at that index.
tup2 = (1, 2, 3, 4, 5, 6, 7 )
tup1[0] : physics
tup2[1:5] : [2, 3, 4, 5]
Tuple Assignment :
• Once in a while, it is useful to perform multiple assignments in a single statement
and this can be done with tuple assignment :
• >>> a,b = 3,4
• >>> print a 3
• >>> print b 4
• >>> a,b,c = (1,2,3),5,6
• >>> print a (1, 2, 3)
• >>> print b 5
• >>> print c
• The left side is a tuple of variables; the right side is a tuple of values. Each value is
assigned to its respective variable. All the expressions on the right side are
evaluated before any of the assignments. This feature makes tuple assignment
quite versatile. Naturally, the number of variables on the left and the number of
values on the right have to be the same:
• Such statements can be useful shorthand for multiple assignment statements, but
care should be taken that it doesn’t make the code more difficult to read.
• One example of tuple assignment that improves readibility is when we want to swap
the values of two variables. With conventional assignment statements, we have to
use a temporary variable. For example, to swap aand b:
Tuples as return values :
• Functions can return tuples as return values. For example, we could write a function that swaps two parameters :
def swap(x, y):
return y, x
• Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
• Basic tuples operations, Concatenation, Repetition, in Operator, Iteration :
• 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.
Built-in Tuple Functions :
• Python includes the following tuple functions-
Tuplelen()Method
Description
• The len() method returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method-
len(tuple)
Parameters
tuple - This is a tuple for which number of elements to be counted.
Return Value
• This method returns the number of elements in the tuple.
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc') print ("First tuple length : ",
len(tuple1))
print ("Second tuple length : ", len(tuple2))
Tuplemax()Method
Description
• The max() method returns the elements from the tuple with maximum value.
Syntax
• Following is the syntax for max() method-
max(tuple)
Parameters
tuple - This is a tuple from which max valued element to be returned.
Return Value
• This method returns the elements from the tuple with maximum value.
Example
• The following example shows the usage of max() method.
• When we run the above program, it produces the following result-
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1)) print ("Max value element : ", max(tuple2)
Tuple min() Method
Description
• The min() method returns the elements from the tuple with minimum
value.
Syntax
• Following is the syntax for min() method-
min(tuple)
Parameters
tuple - This is a tuple from which min valued element is to be returned.
Return Value
• This method returns the elements from the tuple with minimum value.
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("min value element : ", min(tuple1)) print ("min value element :
", min(tuple2))
Tupletuple()Method
Description
• The tuple() method converts a list of items into tuples.
Syntax
Following is the syntax for tuple() method-
tuple( seq )
Parameters
seq - This is a tuple to be converted into tuple.
Return Value
• This method returns the tuple.
list1= ['maths', 'che', 'phy', 'bio'] tuple1=tuple(list1)
print ("tuple elements : ", tuple1)
o/p
tuple elements : ('maths', 'che', 'phy', 'bio')
Dictionary
• 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:
• { }.
• Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
Accessing Values in a dictionary :
• To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
Following is a simple example.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
o/p
dict['Name']: Zara
dict['Age']: 7
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 as shown in a simple example given below.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"
# Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
o/p
dict['Age']: 8 dict['School']: DPS School
----------------------------------------------------------------------------------------------------------------------------------
Deleting Elements from Dictionary :
• You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also
delete entire dictionary in a single operation.
• To explicitly remove an entire dictionary, just use the del statement. Following is a simple example-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name' dict.clear() # remove all entries in dict del dict # delete entire
dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Note: An exception is raised because after del dict, the dictionary does not exist anymore.
Properties of Dictionary keys :
• Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects. However, same is not true for the keys.
• There are two important points to remember about dictionary keys-
A. More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins.
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
o/p
dict['Name']: Manni
B. Keys must be immutable. This means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed.
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
o/p
Traceback (most recent call last): File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7}
TypeError: list objects are unhashable
Operations in Dictionary :
• The del statement removes a key-value pair from a dictionary. For
example, the following dictionary
• contains the names of various fruits and the number of each fruit in stock:
Syntax
• Following is the syntax for len() method-
len(dict)
Example
• The following example shows the usage of len() method.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Length : %d"
% len (dict))
• When we run the above program, it produces the following result-
Length : 3
Dictionarystr()Method
Description
• The method str() produces a printable string representation of a
dictionary.
Syntax
• Following is the syntax for str() method −
str(dict)
Parameters
dict - This is the dictionary.
Return Value
• This method returns string representation.
Example
• The following example shows the usage of str() method.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Equivalent String :
%s" % str (dict))
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
Dictionary type() Method
Description
• The method type() returns the type of the passed variable. If
passed variable is dictionary then it would return a dictionary type.
Syntax
• Following is the syntax for type() method-
type(dict)
Parameters
dict - This is the dictionary.
Return Value
• This method returns the type of the passed variable.
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} print ("Variable Type :
%s" % type (dict))
o/p
Variable Type : <type 'dict'>
• Python includes the following dictionary methods-
Dictionaryclear()Method
Description
• The method clear() removes all items from the dictionary.
Syntax
Following is the syntax for clear() method-
dict.clear()
Parameters
NA
Return Value
• This method does not return any value.
Example :
dict = {'Name': 'Zara', 'Age': 7} print ("Start Len : %d" % len(dict)) dict.clear()
print ("End Len : %d" % len(dict))
o/p
Start Len : 2
End Len : 0
Dictionary copy() Method
Description
• The method copy() returns a shallow copy of the dictionary.
Syntax
• Following is the syntax for copy() method-
dict.copy()
Parameters
NA
Return Value
• This method returns a shallow copy of the dictionary.
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'} dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
o/p:
New dictionary : {'Name': 'Manni', 'Age': 7, 'Class':'First'}
NOTE:
• Python provides two types of copy i.e. 1)shallow 2)deep
Shallow Copy
• A shallow copy creates a new object which stores the reference
of the original elements.
• So, a shallow copy doesn't create a copy of nested objects,
instead it just copies the reference of nested objects. This
means, a copy process does not recurse or create copies of
nested objects itself.
--------------------------------------------------------------------------------
-------------------
Deep Copy
• A deep copy creates a new object and recursively adds the
copies of nested objects present in the original elements.
• The deep copy creates independent copy of original object and
all its nested objects.
Dictionary fromkeys() Method :
Description
• The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Syntax
Following is the syntax for fromkeys() method-
dict.fromkeys(seq[, value]))
Parameters
seq - This is the list of values which would be used for dictionary keys preparation.
value - This is optional, if provided then value would be set to thisvalue
Return Value
• This method returns the list.
Example:
seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict)) dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict)
Dictionary get() Method
Description
• The method get() returns a value for the given key. If the key is not
available then returns default value None.
Syntax
• Following is the syntax for get() method-
dict.get(key, default=None)
Parameters
• key - This is the Key to be searched in the dictionary.
• default - This is the Value to be returned in case key does not exist.
Return Value
• This method returns a value for the given key. If the key is not available,
then returns default value as None.
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
Dictionary items() Method
Description
• The method items() returns a list of dict's (key, value) tuple pairs.
Syntax :
• Following is the syntax for items() method-
dict.items()
Parameters
NA
Return Value
• This method returns a list of tuple pairs.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
o/p
Value : [('Age', 7), ('Name', 'Zara')]
Dictionary keys() Method :
Description
• The method keys() returns a list of all the available keys in the
dictionary.
Syntax
• Following is the syntax for keys() method-
• dict.keys()
Parameters
NA
Return Value
• This method returns a list of all the available keys in the dictionary.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
o/p
Value : ['Age', 'Name']
Dictionary setdefault() Method :
• The method setdefault() is similar to get(), but will set
dict[key]=default if the key is not already in dict.
Syntax
• Following is the syntax for setdefault() method-
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.
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None)) print ("Value : %s"
% dict.setdefault('Sex', None)) print (dict)
Dictionary update() Method
Description
• The method update() adds dictionary dict2's key-values pairs in to dict.
This function does not return anything.
Syntax
• Following is the syntax for update() method-
dict.update(dict2)
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
• This method does not return any value.
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' } dict.update(dict2)
print ("updated dict : ", dict)
o/p
updated dict : {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
Dictionaryvalues()Method
Description
• The method values() returns a list of all the values available in a given
dictionary.
Syntax
• Following is the syntax for values() method-
dict.values()
Parameters
• NA
Return Value
• This method returns a list of all the values available in a given dictionary.
Example
• The following example shows the usage of values() method.
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'} print ("Values : ",
list(dict.values()))
• When we run above program, it produces following result-
Values : ['female', 7, 'Zara']
Files
• Python provides basic functions and methods necessary to manipulate files by
default. You can do most of the file manipulation using a file object.
The open Function
• Before you can read or write a file, you have to open it using Python's built-in open()
function. This function creates a file object, which would be utilized to call other
support methods associated with it.
Syntax
• file object = open(file_name [, access_mode][, buffering])
• Here are parameter details-
• file_name: The file_name argument is a string value that contains the name of the
file that you want to access.
• access_mode: The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc.
• A complete list of possible values is given below in the table. This is an optional
parameter and the default file access mode is read (r).
• buffering: If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the
buffering value as an integer greater than 1, then buffering action is performed with
the indicated buffer size. If negative, the buffer size is the system default (default
behavior).
• The File Object Attributes :
• Once a file is opened and you have one file object, you can get various
information related to that file.
• Here is a list of all the attributes related to a file object-
• The tell() method tells you the current position within the file; in other
words, the next read or write will occur at that many bytes from the
beginning of the file.
• The seek(offset[, from]) method changes the current file position. The
offset argument indicates the number of bytes to be moved. The from
argument specifies the reference position from where the bytes are to be
moved.
import os
# Create a directory "test" os.mkdir("test")
The chdir() Method
• You can use the chdir() method to change the current
directory.
• The chdir() method takes an argument, which is the name of
the directory that you want to make the current directory.
Syntax
os.chdir("newdir")
Example
• Following is an example to go into "/home/newdir" directory-
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
The getcwd() Method
• The getcwd() method displays the current working directory.
Syntax :
os.getcwd()
import os
# This would give location of the current directory os.getcwd()
---------------------------------------------------------------------------------------------------------
The rmdir() Method
• The rmdir() method deletes the directory, which is passed as an argument
in the method. Before removing a directory, all the contents in it should
beremoved.
Syntax :
os.rmdir('dirname')
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
• QUICK REVISION OF UNIT III :
• A list is an ordered set of values, where each value is identified
by an index.
• Important thing about a list is that the items in a list need not be
of the same type.
• Lists are mutable .
• An assignment to an element of a list is called item assignment
• Tuple are very similar to lists with only difference that element
values of a tuple can not be changed and tuple elements are put
between parentheses instead of square bracket.
• append method used to add element in list at last position .
• tuple is a sequence of immutable Python objects.
• Dictionary :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.
• More than one entry per key is not allowed.
• Keys must be immutable.