KEMBAR78
DSA Lab - 1 | PDF | Data Type | String (Computer Science)
0% found this document useful (0 votes)
5 views16 pages

DSA Lab - 1

Uploaded by

gang g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

DSA Lab - 1

Uploaded by

gang g
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CL – 2021 Object Oriented Data Structures - LAB

OBJECT ORIENTED DATA


STRUCTURES
(CL-2021)
LABORATORY MANUAL
FALL 2025

LAB 01
Introduction to Data Structures using Python
Instructor: Dr Burhan Khan

________________________________________ __________ ___


STUDENT NAME ROLL NO SEC

______________________________________
FACULTY'S SIGNATURE & DATE

MARKS AWARDED:

_______________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (FAST-NUCES), KARACHI

NUCES, KARACHI Fall-2025 1


CL – 2021 Object Oriented Data Structures - LAB

Lab Session 01: Introduction to Data Structures using Python


OBJECTIVE:
• To understand abstract data types and data structures.
• To know about the difference between primitive and non-primitive data structures.
• To learn how to use python.

INTRODUCTION
In this course you will learn about using Python specifically in the context of data structures.
In this lab we will cover the following objectives:

• Abstract Data Type and Data Structures


• Primitive Data Structures
1. Integers
2. Float
3. Strings
4. Boolean
• Non-Primitive Data Structures
1. Arrays
2. Lists
3. Tuples
4. Dictionary
5. Sets

ABSTRACT DATA TYPE AND DATA STRUCTURES


As you read in the introduction, data structures help you to focus on the bigger picture rather
than getting lost in the details. This is known as data abstraction. Now, data structures are

NUCES, KARACHI Fall-2025 2


CL – 2021 Object Oriented Data Structures - LAB

actually an implementation of Abstract Data Types or ADT. This implementation requires a


physical view of data using some collection of programming constructs and basic data types.

Generally, data structures can be divided into two categories in computer science: primitive
and non-primitive data structures. The former are the simplest forms of representing data
storing single value with immutability, whereas the latter are more advanced: they contain
the primitive data structures within more complex data structures to store collection of data.

A. 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 and Boolean.

1. Integers

You can use an integer to represent numeric data, and more specifically, whole numbers from
negative infinity to infinity, like 4, 5, or -1.

2. Float

"Float" stands for 'floating point number'. You can use it for rational numbers, usually ending
with a decimal figure, such as 1.11 or 3.14.

Example: Take a look at the following chunk and try out some of the integer and float
operations!

Python code Output? (to be


filled by student)
#Floats
x=-4.0
y=5.0
#Addition
print(x+y)
#Subtraction
print(x-y)
#Multiplication
print(x*y)
#Return the quotient
print(x/y)
#Return the remainder
print(x%y)
#Return Absolute value
print(abs(x))
# x to the power y
print(x ** y)

NUCES, KARACHI Fall-2025 3


CL – 2021 Object Oriented Data Structures - LAB

3. String

Strings are collections of alphabets, words or other characters. In Python, you can create
strings by enclosing a sequence of characters within a pair of single or double quotes. For
example: 'cake', "cookie", etc. You can also apply the + operations on two or more strings to
concatenate them, just like in the example below:

x = 'Cake'
y = 'Cookie'

1. x + ' & ' + y

2. You can use * to repeat a string a certain number of times: x * 2

3. You can also slice strings, which means that you select parts of strings:
Range Slicing: z1 = x[2:] print(z1)
Print(z1)

4. Slicing: z2 = y[0] + y[1]


print(z2)

5. Strings can also be alpha-numeric characters, but that the + operation still is used to
concatenate strings.
x = '4', y= '2'
x + y = '42'
Python has many built-in methods or helper functions to manipulate strings. Replacing a
substring, capitalizing certain words in a paragraph, finding the position of a string within
another string are some common string manipulations. Check out some of these:

6. Capitalize strings
str.capitalize('cookie')

7. Retrieve the length of a string in characters. Note that the spaces also count towards the
final result:
str1 = "Cake 4 U"
str2 = "404"
len(str1)

NUCES, KARACHI Fall-2025 4


CL – 2021 Object Oriented Data Structures - LAB

8. Check whether a string consists of only digits


str1.isdigit()

str2.isdigit()

9. Replace parts of strings with other strings


str1.replace('4 U', str2)

10. Find substrings in other strings; Returns the lowest index or position within the string at
which the substring is found:
str1 = 'cookie'
str2 = 'cook'
str1.find(str2)

11. The substring 'cook' is found at the start of 'cookie'. As a result, you refer to the position
within 'cookie' at which you find that substring. In this case, 0 is returned because you start
counting positions from 0!
str1 = 'I got you a cookie', str2 = 'cook'
str1.find(str2)

4. Boolean

This built-in data type that can take up the values: True and False, which often makes them
interchangeable with the integers 1 and 0. Booleans are useful in conditional and comparison
expressions, just like in the following examples:

x = 4, y = 2
x == y

x>y

x=4
y=4
z = (x==y) #Comparision expression

if z: #Conditional on truth/false value of ‘z’


print(“Cookie”)
else:
print(“No Cookie”)

NUCES, KARACHI Fall-2025 5


CL – 2021 Object Oriented Data Structures - LAB

Data Type Conversion:

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)

Implicit Data Type Conversion

x = 4.0 # A float
y=2 # An integer
z = x/y # Divide `x` by `y`
type(z) # Check the type of `z`

Explicit Data Type Conversion

This type of data type conversion is user defined, which means you must explicitly inform the
compiler to change the data type of certain entities.
x=2
y = "The Godfather: Part "
fav_movie = y + x

The above example gave you an error because the compiler does not understand that you are trying
to perform concatenation or addition, because of the mixed data types. You have an integer and a
string that you're trying to add together. There's an obvious mismatch. To solve this, you'll first need
to convert the int to a string to then be able to perform concatenation.
x=2
y = “The Godfather: Part”
fav_movie = (y) + str(x)
print(fav_movie)

B. Non-Primitive Data Structures

Non-primitive types are the sophisticated members of the data structure family. They don't
just store a value, but rather a collection of values in various formats. In the traditional

NUCES, KARACHI Fall-2025 6


CL – 2021 Object Oriented Data Structures - LAB

computer science world, the non-primitive data structures are divided into: Arrays, Lists and
Files.

1. Array
First off, arrays in Python are a compact way of collecting basic data types, all the entries in
an array must be of the same data type. However, arrays are not all that popular in Python,
unlike the other programming languages such as C++ or Java. In general, when people talk of
arrays in Python, they are actually referring to lists.

However, there is a fundamental difference between them, and you will see this in a bit. For
Python, arrays can be seen as a more efficient way of storing a certain kind of list. This type
of list has elements of the same data type, though.

In Python, arrays are supported by the array module and need to be imported before you
start initializing and using them. The elements stored in an array are constrained in their data
type.

The data type is specified during the array creation and specified using a type code, which is
a single character like the, I you see in the example below:

import array as arr


a = arr.array("I",[3,6,9])
print(type(a))

2. List
Lists in Python are used to store collection of heterogeneous items. These are mutable, which
means that you can change their content without changing their identity. You can recognize
lists by their square brackets [ and ] that hold elements, separated by a comma ,. Lists are
built into Python: you do not need to invoke them separately.
x=[] #Empty List
print(type(x))
x1 = [1,2,3]
print(type(x1))
x2 = list([1,'apple',3])
type(x2)
print(x2[1])
x2[1] = 'orange'
print(x2)

Python provides many methods to manipulate and work with lists. Adding new items to a list,
removing some items from a list, sorting or reversing a list are common list manipulations.
Let's see some of them in action:
• Add 11 to the list_num list with append(). By default, this number will be added to
the end of the list.

NUCES, KARACHI Fall-2025 7


CL – 2021 Object Oriented Data Structures - LAB

list_num = [1,2,45,6,7,2,90,23,435]
list_char = ['c','o','o','k','i','e']
list_num.append(11)
# Add 11 to the list, by default adds to the last position
print(list_num)
[1, 2, 45, 6, 7, 2, 90, 23, 435, 11]
Use insert ( ) to insert 11 at index or position 0 in the list_num list
list_num.insert(0, 11) print(list_num)
[11, 1, 2, 45, 6, 7, 2, 90, 23, 435, 11]
Remove the first occurence of 'o' from list_char with the help of remove()
list_char.remove('o') print(list_char)
['c', 'o', 'k', 'i', 'e']
Remove the item at index -2 from list_char
list_char.pop(-2) # Removes the item at the specified position
print(list_char)
['c', 'o', 'k', 'e']
# In-place sorting
list_num.sort()
print(list_num)
[1, 2, 2, 6, 7, 11, 11, 23, 45, 90, 435]
Reverse list
list.reverse(list_num)
print(list_num)
[435, 90, 45, 23, 11, 11, 7, 6, 2, 2, 1]

Example (Write the corresponding O/Ps below):

➢ fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']


➢ fruits.count('apple')

➢ fruits.count('tangerine')

➢ fruits.index('banana')

➢ fruits.index('banana', 4) # Find next banana starting a position 4

➢ fruits.reverse()

➢ fruits

➢ fruits.append('grape')

➢ fruits.sort()

➢ fruits

➢ fruits.pop()

NUCES, KARACHI Fall-2025 8


CL – 2021 Object Oriented Data Structures - LAB

3. Tuples
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
Tuples are another standard sequence data type. The difference between tuples and list is
that tuples are immutable, which means once defined you cannot delete, add or edit any
values inside it. This might be useful in situations where you might pass the control to
someone else, but you do not want them to manipulate data in your collection, but rather
maybe just see them or perform operations separately in a copy of the data. Let's see how
tuples are implemented:

# Empty tuple
my_tuple = ()
print(my_tuple)
# Output: ()

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)
# Output: (1, 2, 3)

# Tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# Output: (1, "Hello", 3.4)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# Output: ("mouse", [8, 4, 6], (1, 2, 3))

Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.

my_tuple = ('p','e','r','m','i','t')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])
Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".

NUCES, KARACHI Fall-2025 9


CL – 2021 Object Oriented Data Structures - LAB

my_tuple = ('p','r','o','g','r','a','m','i','z')

# Elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# Elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple[:-7])

# Elements 8th to end


# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Slicing can be best visualized by considering the index to be between the elements as shown
below. So, if we want to access a range, we need the index that will slice the portion from the
tuple.

4. 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]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])

NUCES, KARACHI Fall-2025 10


CL – 2021 Object Oriented Data Structures - LAB

NUCES, KARACHI Fall-2025 11


CL – 2021 Object Oriented Data Structures - LAB

5. Sets
A set is created by placing all the items (elements) inside curly brackets, separated by comma
or by using the built in function set().

Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in
Python used to store collections of data. A set is a collection which is unordered,
unchangeable, and unindexed. Set items are unchangeable, but you can remove items and
add new items.

x_set = set(‘CAKE&COKE’)
y_set = set(‘COOKIE’)
print(x_set)

print(y_set)

print(x_set|y_set) #Unique elements in x_set or y_set or both

print(x_set&y_set) #Elements in both x_set or y_set

my_set = {1,2,3} #set of integers


print(my_set)
my_set = {1.0, “Hello”, (1,2,3)} #set of mixed
print(my_set)
Python Set Operations
# Initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
print(A | B)
A.union(B)
# Use union function on B
B.union(A)
# use & operator
print(A & B)
# Output: {4, 5}
#Intersection
A.intersection(B)
# Use - operator on A
print(A - B)

Note:
In a linear data structure, the data items are organized sequentially or in other words linearly.
The data items are traversed serially one after another and all the data items in a linear data
structure can be traversed during a single run. However, in non-linear data structures the data

NUCES, KARACHI Fall-2025 12


CL – 2021 Object Oriented Data Structures - LAB

items are not organized sequentially which means the elements could be connected to more
than one element to reflect a special relationship among these items. All the data items in a
non-linear data structure may not be traversed during a single run.

NUCES, KARACHI Fall-2025 13


CL – 2021 Object Oriented Data Structures - LAB

Lab Report:

(It is recommended to write Lab Report in bullet Form.)

___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

NUCES, KARACHI Fall-2025 14


CL – 2021 Object Oriented Data Structures - LAB

Assessment Rubrics for Lab

Student Name(s): Roll # Section

Method: Lab reports and instructor observation during Lab sessions


Outcome Assessed:
a. An ability to conduct experiments, as well as to analyze and interpret data. (P4/PLO 4).
b. An ability to work effectively as an individual or in a team. (A5/PLO 9).
c. Ability to demonstrate the use of the techniques, skills, and modern engineering tools necessary
for engineering practice. (P4/PLO 5).
d. An ability to design a solution for an open-ended lab with appropriate considerations for public
health and safety, cultural, societal, or environmental factors. (C5/PLO3)

Performance Does not meet expectation Meets expectation Exceeds expectation Applicable Marks
(0-1) (2-3) (4-5) /Not
Applicable
(NA)
1. Realization of Incapable of selecting Needs guidance to select relevant Selects relevant equipment to the
Experiment [c] relevant equipment to equipment to the experiment and experiment, develops setup
conduct the experiment,
to develop equipment connection diagrams of equipment
equipment connection or
wiring diagrams. or wiring diagrams. connections or wiring.
2. Individual or Distracts or discourages Cooperates with other group Actively engages and cooperates
Teamwork [b] other group members from members in a reasonable manner, with other group members in an
conducting the experiment, or as an individual, perform the effective manner, or actively
or look discouraged or experiment in a manner guided. perform an experiment in an
distracted as an individual. organized and professional
manner as an individual.
3. Conducting Unable to calibrate Calibrates equipment, examines Does proper calibration of
Experiment [a] appropriate equipment, and equipment moving parts, and equipment, carefully examines
equipment operation is operates the equipment with equipment moving parts, and
substantially wrong. minor error. ensures smooth operation and
process.
4. Laboratory Safety Disregards safety rules and Observes safety rules and Respectfully and carefully
Rules [c] procedures. procedures with minor deviation. observes safety rules and
procedures
5. Data Collection Does not know how to plan Plans data collection to achieve Plans data collection to achieve
[a] data collection to achieve experimental objectives, and experimental objectives, and
experimental goals; data collects complete data with minor conducts an orderlyand a
collected is incomplete and error. complete data collection.
contain errors.
6. Data Analysis [a] Unable to conduct simple Conducts simple computations Accurately conducts simple
statistical analysis on and statistical analysis using computations and statistical
collected data; no attempt to collected data with minor error; analysis using collected data;
correlate experimental reasonably correlates correlates experimental results to
results with known experimental results to known known theoreticalvalues;
theoretical values; incapable theoretical values; attempts to accounts for measurement errors
of explaining measurement account for measurement errors and parameters that affect
errors or parameters that and parameters that affect experimental results.
affect the experimental experimental results.
results.
7. Design of Unable to design the Able to design and partially Able to design and implement the
Experiment [d] complete solution of open- implement the complete solution complete solution of open-ended
ended problem with safety, of open-ended problem with problem with safety, health and
health and environment safety, health and environment environment related
related considerations. related considerations. considerations.
Total

Lab Engineer/Faculty

NUCES, KARACHI Fall-2025 15


CL – 2021 Object Oriented Data Structures - LAB

Name: __________________

Signature: ____________

Date: ____________________

NUCES, KARACHI Fall-2025 16

You might also like