Practical # 2
Practical # 2
EMAN SHAHID
DATA STRUCTURES
• Data structures are a way of organizing and storing data so that they can be
accessed and worked with efficiently. They define the relationship between
the data, and the operations that can be performed on the data.
PRIMITIVE DATA STRUCTURES
PRIMITIVE DATA STRUCTURES
These are the most primitive or the basic data structures. They are the building
blocks for data manipulation and contain pure, simple values of a data. Python
has four primitive variable types:
• Integers
• Float
• Strings
• Boolean
NUMBERS
• Mathematical Constants
LAB TASKS:
• Assume string
variable a holds
'Hello' and
variable b holds
'Python'
STRING
FORMATTING
OPERATOR
BUILT-IN STRING METHODS
BOOLEAN
The simplest build-in type in Python is the bool type, it represents the truth
values False and True.
NON PRIMITIVE DATA STRUCTURES
NON PRIMITIVE DATA STRUCTURE
• Arrays
• List
• Tuples
• Dictionaries
• Sets
• Files
ARRAYS
• In Python, arrays
are supported by
the array module
and need to be
imported before
you start initializing
and using them.
Array functions
• array.insert(i, x)
Insert a new item with value x in the array before position i.
Negative values are treated as being relative to the end of the
array.
• array.pop([i])
• Removes the item with the index i from the array and returns it.
The optional argument defaults to -1, so that by default the last
item is removed and returned.
• array.remove(x)
Remove the first occurrence of x from the array.
• array.reverse()
Reverse the order of the items in the array.
• array.tobytes()
Convert the array to an array of machine values and return the bytes
representation (the same sequence of bytes that would be written to a file by
the tofile() method.)
New in version 3.2: tostring() is renamed to tobytes() for clarity.
• array.tofile(f)
Write all items (as machine values) to the file object f.
• array.tolist()
Convert the array to an ordinary list with the same items.
• array.tostring()
• array.count(x)
Return the number of occurrences of x in the array.
• array.fromfile(f, n)
Read n items (as machine values) from the file object f and append them to the
end of the array.
• array.append(x)
Append a new item with value x to the end of the array.
• array.fromlist(list)
Append items from the list.
• array.fromunicode(s)
Extends this array with data from the given unicode string.
• array.index(x)
Return the smallest i such that i is the index of the first occurrence of x in the
array.
LAB TASK:
• The list is a 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 items in a list need not be of the same
type.
CREATING LIST
• To build a list, just put some expressions in square brackets. The syntax is:
Syntax:
lst1 = [ ] # lst1 is the name of the list
lst2 = [expression1 , …. , expression_N]
Example:
lst1 = ['computersc', 'IT', 'CSE']
st2 = [1993, 2016]
lst3 = [2, 4, 6, "g", "k", "s"]
ACCESSING LISTS VALUES
• Example
lst1 = ['computersc', 'IT', 'CSE'];
lst2 = [1993, 2016];
lst3 = [2, 4, 6, "g", "k", "s"];
print ("lst1[0]", lst1[0])
print ("lst3[2:4]", lst3[2:4])
• Output:
lst1[0] computersc
lst3[2:4] [6, 'g']
UPDATING LIST ELEMENTS
Example:
lst1 = ['computersc', 'IT', 'CSE'];
print ("Second value of the list is:")
print (lst1[1])
lst1[1] = 'Robotics'
print ("Updated value in the second index of list is:")
print (lst1[1])
Output:
Second value of the list is:
IT
Updated value in the second index of list is:
Robotics
DELETE ELEMENTS FROM LISTS
To remove an element from the list, we can use the del-statement. The syntax for
deleting an element from a list is:
Syntax:
del list_name[index_val];
LAB TASK:
Tuples are immutable lists and cannot be changed in any way once it is created.
Some of the characteristics features of Tuples are:
•Tuples are defined in the same way as lists.
•They are enclosed within parenthesis and not within square braces.
•Elements of the tuple must have a defined order.
•Negative indices are counted from the end of the tuple, just like lists.
•Tuple also has the same structure where the values are separated by commas
Example:
tupl1 = ('computersc', 'IT', 'CSE');
ACCESSING VALUES IN TUPLES
Example:
tupl1 = ('computersc', 'IT', 'CSE');
tupl2 = (1993, 2016);
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
print ("tupl1[0]", tupl1[0])
print ("tupl3[2:4]", tupl3[2:4])
Output:
tupl1[0] computersc
tupl3[2:4] (6, 8)
UPDATING TUPLES
Example:
tupl1 = (2, 3, 4);
tupl2 = ('ab', 'cd');
tupl3 = tupl1 + tupl2
print (tupl3)
Output:
(2, 3, 4, 'ab', 'cd')
• Create tuples and manipulate it using built-in functions, operation and slicing.
DICTIONARY
• Variables provide us a way to store data while the program runs, if we want out
data to persist even after the termination of the program, we have to save it to a
file.
• File Opening In Python
open() function is used to open a file in Python. It's mainly required two arguments,
first the file name and then file opening mode.
Syntax:
file_object = open(filename [,mode] [,buffering])
In the above syntax the parameters used are:
•filename: It is the name of the file.
•mode: It tells the program in which mode the file has to be open.
•buffering: Here, if the value is set to zero (0), no buffering will occur while
accessing a file, if the value is set to top one (1), line buffering will be performed
while accessing a file.
MODES OF
OPENING FILES
CREATING SETS
setx = set()
n = set([0, 1, 2, 3, 4, 5])
• color_set = set()
• Add a single member
color_set.add("Red")
If an attempt to open a file fails then open returns a false value, otherwise it
returns a file object that provides various information related to that file.
Example:
# file opening example in Python
fo = open("sample.txt", "w")
print ("File Name: ", fo.name)
print ("Mode of Opening: ", fo.mode)
print ("Is Closed: ", fo.closed)
Output:
File Name: sample.txt
Mode of Opening: w
Is Closed: False
FILE READING IN PYTHON
• For reading and writing text data different text-encoding schemes are used
such as ASCII (American Standard Code for Information Interchange), UTF-8
(Unicode Transformation Format), UTF-16.
• Once a file is opened using open() method then it can be read by a method
called read().
Example:
# read the entire file as one string
with open('filename.txt') as f:
data = f.read()
# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
print(line, end=' ')# process the lines
WRITING A FILE
IN PYTHON
• Closing a file
file_object.close();
TYPE CASTING
DATA TYPE CONVERSION
• When you change the type of an entity from one data type to another, this is
called "typecasting". There can be two kinds of data conversions
possible: implicit termed as coercion and explicit, often referred to as casting.
CHECKING DATA TYPE:
To check the type of an object in Python, use the built-in type() function, just
like in the lines of code below:
i = 4.0
type(i)
Output: float
IMPLICIT DATA TYPE CONVERSION
# A float
x = 4.0
# An integer
y=2
# Divide `x` by `y`
z = x/y # Check the type of `z`
type(z)
Output: float
EXPLICIT DATA TYPE CONVERSION
• This type of data type conversion is user defined, which means you have to
explicitly inform the compiler to change the data type of certain entities.
Note that it might not always be possible to convert a data type to another. Some built-in
data conversion functions that you can use here are: int(), float(), and str().
x=2
y = "The Godfather: Part "
fav_movie = (y) + str(x)
print(fav_movie)
Output: The Godfather: Part 2
LAB TASK:
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))
OUTPUT
120
LAB TASKS:
• Write a program for Fibonacci series with simple function and recursion.
• Write a Python function to sum all the numbers in a list
• Write a Python program to reverse a string.
• Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
• Write a Python program to check if a given key already exists in a dictionary.
CLASS TASKS: