0% found this document useful (0 votes)
0 views11 pages

DSA Lab 2

The lab report details the process of inserting an element at any location in an array using Python. It outlines the objectives, required equipment, and provides a theoretical background on arrays, including methods for creating and manipulating them. The report concludes with practical tasks and code examples demonstrating array insertion and other operations, emphasizing the importance of dynamic data management.

Uploaded by

amjidprogrammer
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)
0 views11 pages

DSA Lab 2

The lab report details the process of inserting an element at any location in an array using Python. It outlines the objectives, required equipment, and provides a theoretical background on arrays, including methods for creating and manipulating them. The report concludes with practical tasks and code examples demonstrating array insertion and other operations, emphasizing the importance of dynamic data management.

Uploaded by

amjidprogrammer
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/ 11

UNIVERSITYOF ENGINEERING AND TECHNOLOGY

TAXILA

Submitted To:
Engr. Iqra Jabeen

Submitted By:
Amjid Khan (23-TE-86)

Subject:
Data Structure and Algorithms Lab

DEPARTMENT OF TELECOMMUNICATION
ENGINEERING
1

Lab Report: 2
Computation and Implementation of Python code for Inserting an
element at any location in an Array.

Objective:
➢ Modify the array by adding a new element at a specific index.
➢ Maintain the order and integrity of existing elements.
➢ Support dynamic data structure management.
➢ Enable precise control over data insertion.

Equipment Required:
➢ Computer/Laptop with at least 4 GB RAM.
➢ Python 3.x installed and configured.
➢ IDE/Text Editor like PyCharm, VS Code, or Jupyter Notebook.
➢ NumPy library (optional) for advanced array handling.
➢ Internet connection for downloading resources and accessing documentation.

Procedure:
➢ Open Computer System.
➢ Go to all the programs.
➢ Open python.
➢ Create a new file with the extension .py.
➢ Write all the required code and then run the module.

Theory:

Array:
An array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. This makes it easier to calculate the position of
2

each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array).

Creating arrays in python:

Without Alias
Using Alias
import array as arr
Using *
import array as arr
from array import *

Declaring Arrays:
Python provides an array module to declare a set of data as an array.

Method: 1
arrayName = array(typecode, [initializers])

typecode - the codes that are used to define the type of value the array will hold.
3

Type code C type Python type Minimum size in byte


“b” Signed char Int 1
“B” Unsigned char Int 1
“u” Py_unicode Unicode character 2
“h” Signed short Int 2
“H” Unsigned short Int 2
“I” Signed int Int 2
“I” Unsigned int Int 2
“l” Signed long Int 4
“L” Unsigned long Int 4
“q” Signed long long Int 8
“Q” Unsigned long long Int 8
“f” Float Float 4
“d” Double float 8

Initializers - a set of similar type of data.


import array
a = array.array("i", [1, 2, 3])
print(a[0])
print(a)
from array import array
array1 = array('i', [10, 20, 30, 40, 50, 60, 70, 80, 90])
for x in array1:
print(x)

output:
4

Method#2:
import array as arr
a = arr.array('i',[1,2,3,4,5])
print(a[0])
output:

Method#3:
from array import *
a = array ('i',[1,2,3,4,5])
print(a[0])
output:

Accessing Array Elements:


An element is accessed by indexing the array name. This is done by placing the element's index
within square brackets after the array's name. For example.
Print arr([0])
Following is an example, which will use all the above-mentioned two concepts viz. declaration,
and accessing arrays
Example:
from array import array
array1 = array('i', [10, 20, 30, 40, 50])
print(array1[0])

output:
5

The Length of an Array:


Use the len() method to return the length of an array (the number of elements in an array).
from array import array
array1 = array('i', [10, 20, 30, 40, 50])
print(array1)
print(len(array1))
output:

Looping in an array:
import array as arr
a=arr.array('i',[1,2,3,4,5])
print('Integer array: ',end=" ")
for i in range (0,5):
print(a[i], end=" ")
print()
output:

Insertion Operation in arrays:


An insert function allows us to add one or more elements to an array. Here, a new element can
be inserted at the beginning, middle, end, or any index we state. Insert operation is to insert one
or more data elements into an array. Based on the requirement, a new element can be added at
the beginning, end, or any given array index.
6

from array import*


array1=array('i',[1,2,3,4,5])
array1.insert(0,12)
for x in array1:
print(x)
output:

append (): This function is used to add the value mentioned in its arguments at the end of the
array.
insert(i,x) :This function is used to add the value(x) at the ith position specified in its argument.
index():- This function returns the index of the first occurrence of the value mentioned in the
arguments.

reverse():- This function reverses the array.


7

Lab Tasks:
1. Implement python code for insertion at given index in an array and generate the following
output.
import array
arr = array.array('i', [1, 2, 4, 5])
print("Printing array before insertion")
for i in range(len(arr)):
print(f"array[{i}] = {arr[i]}")
arr.insert(2, 3)
print("\nPrinting array after insertion")
for i in range(len(arr)):
print(f"array[{i}] = {arr[i]}")

output:

2. Write a python program that inputs an integer array and then inserts the integer value X
in the first position in the array and generates the following output.
import array
arr = array.array('i', [1, 2, 3, 4, 5, 6])
print("Stored Data in Array ::")
for item in arr:
print(item, end=" ")
print()
X = 0
arr.insert(0, X)
print("New Array is ::")
for item in arr:
8

print(item, end=" ")


print()

output:

3. Write a Python program to swap the first and last element of an integer in an array.
import array
arr = array.array('i', [1, 2, 3, 4, 5, 6])
print('Array before swipping:')
for i in arr:
print(i,end=" ")
print("\n")

arr[0], arr[-1] = arr[-1], arr[0]


print("Array after swapping first and last elements:")
for item in arr:
print(item, end=" ")
print()

output:

4. Write a Python program to find the largest and smallest element of an integer in an array.
import array
arr = array.array('i', [10, 3, 45, 7, 22, 99, 1])
print(arr)
print("The largest element of array is: ",max(arr))
print("The smallest element of array is: ",min(arr))
9

output:

5. Write a program in Python to print all even and odd numbers from an array to a new array.
import array
arr = array.array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
even_arr = array.array('i', [x for x in arr if x % 2 == 0])
odd_arr = array.array('i', [x for x in arr if x % 2 != 0])
print("Even numbers array:", even_arr)
print("Odd numbers array:", odd_arr)

output:

6. Write a Python program to generate the following output by keeping the list as an input.
import array
arr = array.array('d', [2.1, 4.5, 3.5, 4.2, 3.3, 5.5])
print(f"First element: {arr[0]}")
print(f"Second element: {arr[1]}")
print(f"Last element: {arr[-1]}")
sub_arr = array.array('d', [arr[2], arr[3], arr[4]])
print(sub_arr)
print(arr)

output:
10

Conclusion:
In this lab, we examined how to insert an element at any location in an array using Python. The
key aspect of this operation involves shifting elements from the insertion point onward to create
space for the new element. This process maintains the order of existing elements while
accommodating the new addition.
We implemented this insertion operation using Python lists, leveraging list slicing and
concatenation to insert the element at the desired index. The code snippet provided illustrates a
straightforward approach to handling this task and considers various edge cases, such as inserting
at the beginning, end, or within the bounds of the list.
In conclusion, the ability to insert elements at specific locations is crucial for a wide range of
applications, including data processing and real-time data management. Python's list operations
simplify this process, making it easy to manipulate arrays dynamically and efficiently.

You might also like