0% found this document useful (0 votes)
39 views

Lists As Arrays

The document discusses various Python programs related to arrays and lists. It covers topics like: 1. Creating arrays and lists and representing them graphically. Arrays store elements of the same type while lists can store heterogeneous elements. 2. Common operations on arrays like appending, inserting, extending, removing elements using methods like append(), insert(), extend(), remove() etc. 3. Other array operations like reversing, counting occurrences of an element, and examples of linear and binary search algorithms. 4. Other numerical programs including calculating square root, GCD, exponentiation and summing elements of an array.

Uploaded by

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

Lists As Arrays

The document discusses various Python programs related to arrays and lists. It covers topics like: 1. Creating arrays and lists and representing them graphically. Arrays store elements of the same type while lists can store heterogeneous elements. 2. Common operations on arrays like appending, inserting, extending, removing elements using methods like append(), insert(), extend(), remove() etc. 3. Other array operations like reversing, counting occurrences of an element, and examples of linear and binary search algorithms. 4. Other numerical programs including calculating square root, GCD, exponentiation and summing elements of an array.

Uploaded by

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

Lists as arrays

A list in Python is just an ordered collection of items which can be of any type.

By comparison an array is an ordered collection of items of a single type.

Lists as arrays
The arrays is a data structure in which the elements are of same data type.

A list in Python is just an ordered collection of items which can be of any type.
By comparison an array is an ordered collection of items of a single type.

The elements in the array are separated by comma and are enclosed within the
square bracket. For example

arr = [10,20,30,40,50]

The arr can be represented by following figure

Fig. 3.9.1 Array representation

Here the values are arranged sequentially as follows –

arr[0] = 10

arr[1] = 20

arr[2] = 30

arr[3] = 40

arr[4] = 50
1. Creation of Arrays
We can create an array using the array name and list of elements. For example

arr = [10,20,30,40]

will create an array containing the elements 10,20,...,40. These elements can be
represented using for loop. Following program represents the array creation and
display of elements.

ArrayDemo.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

Output

Another method of creation of Array

We can also create an array using following method

a = [i for i in range(10)]

2. Operations on Arrays
1. Appending a value

Using append() function we can add the element in the array at the end. For
example

ArrayDemo1.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

arr.append(50)

print("Now The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30

40

Now The elements is array are ...

10

20

30

40

50
>>>

Thus we can see that value 50 is appended in the array.

2. Inserting the element in the list

We can insert the value at any desired location using insert() function. The
syntax is insert(index,value)

For example

ArrayDemo2.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

arr.insert(2,25)

print("Now The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30

40

Now The elements is array are ...

10

20
30

40

>>>

3. Extending the array

We can extend one array by joining another array to it. For that purpose the
extend() function is used. The syntax is

extend(new_array)

For example

ArrayDemo3.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

new_arr = [50,60,70]

arr.extend(new_arr)

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30

40

50
60

70

>>>

4. Removing the element from the array

Any desired element can be deleted from the array using remove() method. The
syntax is

remove(index_of_element)

For example

ArrayDemo4.py

arr = [10,20,30,40]

print("The elements is array are ...").

for i in range(len(arr)):

print(arr[i])

arr.remove(30)

print("Now The elements is array are ...").

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30

40

Now The elements is array are ...


10

20

40

>>>

5. Removing last element from array

For removing the last element from the array then pop() function is used.

Syntax

pop()

For example

ArrayDemo5.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

arr.pop()

print("Now The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30
40

Now The elements is array are ...

10

20

30

>>>

6. Reversing the elements of array

We can reverse the contents of the array using reverse() function

For example

ArrayDemo6.py

arr = [10,20,30,40]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

arr.reverse()

print("Now The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

Output

The elements is array are ...

10

20

30
40

Now The elements is array are ...

40

30

20

10

>>>

7. Counting the occurrence of element in array

We can count the number of times the particular element appears in the array
using the count method.

For example

ArrayDemo7.py

arr = [10,20,30,40,50,20,30,20]

print("The elements is array are ...")

for i in range(len(arr)):

print(arr[i])

print("The element 20 appears for ", arr.count(20)," times in array")

Output

The elements is array are ...

10

20

30

40

50
20

30

20

The element 20 appears for 3 times in array

Illustrative Python Programs


Control Flow, Functions, Strings

Home | All Subjects | EEE Department | Problem Solving and Python Programming
<< Previous
Next >>
Following is a Python program that is used for obtaining the square root of a given
number

Illustrative Programs
AU : Dec.-19, Marks 8

1. quare Root
Following is a Python program that is used for obtaining the square root of a
given number

Python Program

print("Enter the number: ")

num = float(input())

sqrt_num = num ** 0.5

print("The square root of ",num," is ",sqrt_num)

Output
2. GCD
The GCD is a largest integer that can exactly divide both numbers without a
remainder.

The easiest and fastest process consists in decomposing each one of the
numbers in products of prime factors, this is, and we successively divide each
one of the numbers by prime numbers till we reach a quotient that equals 1.

For example -

96 = 2 × 2 × 2 × 2 × 2 × 3

36 = 2 × 2 3 × 3

GCD = 2 × 2 × 3

= 12

Hence GCD of 96 and 36 is 12.

Iterative Python Program

print("Enter first number: ")

a = int(input())

print("Enter second number: ")

b = int(input())
rem = a%b

while rem! = 0:

a=b

b = rem

rem = a%b

print("gcd of given numbers is: ",b)

Output

Recursive Python Program

def gcd(a,b):

c=b

b = a%b

if b = = 0:

return c

else:

return gcd(cb)

print(gcd(96,36))

Output

12
>>>

Cano

3. Exponentiation
Python Program

def expo(base,degree):

result = 1

i=1

while I < = degree:

result = base * result

i+=1

print("Result is ",result)

expo(2,3)

Output

Result is 8

>>>

4. Sum of Numbers
For sum of numbers we have to store the numbers in an array. And by
traversing the elements of array, each number is added with each other. The
resultant sum is then printed.

For example

Consider 5 numbers stored in an array as follows -


Sum = (10 + 20 + 30 + 40 + 50) = 150

Python Program

print("Enter total number of elements in array")

n = int(input())

i=0

sum = 0

a = [i for i in range(n)] #Creation of array

for i in range(0,n):

print("Enter the element: ")

a[i] = int(input())

print("The elements in array are ...")

for i in range(0,n):

print(a[i])

for i in range(0,n):

sum = sum + a[i]

print("The sum of all elements in array",sum)

Output
5. Linear Search
In linear search method, the key element is compared against every element of
the array. If the key element matches with the array element then we declare
element is found otherwise the element is declared as not found.

Python Program

print("Enter total number of elements in array")

n = int(input())

i=0

a = [i for i in range(n)] #Creation of array

for i in range(0,n):

print("Enter the element: ")

a[i] = int(input())
print("The elements in array are ...").

for i in range(0,n):

print(a[i])

print("Enter the key element to be searched ")

key = int(input())

for i in range(0,n):

if a[i] = = key:

found = True

break

else:

found = False

if found = = True:

print("The element is found")

else:

print("The element is not found")

Output
6. Binary Search
The binary search is an efficient searching technique.

Python Program

def binary_search(a,n,key):

low = 0

high = n

while(low < = high):

mid = int((low+high)/2)

if(key == a[mid]):

return mid
elif(key< a[mid]):

high = mid - 1

else:

low = mid + 1

return -1

n = int(input("Enter the size of the list: "))

a = [i for i in range(n+1)] #Creation of array

for i in rnge(0,n):

print("Enter the element: ")

a[i] = int(input())

print(“Enter the element to be searched: ")

k = int(input())

position = binary_search(a,n,k)

if(position ! = -1):

print("Entered number {} is present at position: {}".format(k,position))

Cered number {} is not present in the list".format(k))

Output(Run1)

Enter the size of the list: 5

Enter the element:

10

Enter the element:

20
Enter the element:

30

Enter the element:

40

Enter the element:

50

Enter the element to be searched:

40

Entered number 40 is present at position: 3

>>>

Output(Run2)

Enter the size of the list: 5

Enter the element:

10

Enter the element:

20

Enter the element:

30

Enter the element:

40

Enter the element:

50

Enter the element to be searched:


90

Enter the number 90 is not present in the list

>>>

Explanation on Binary search method

The prerequisite for this searching technique is that the arry should be sorted.

Example :

Aa mentioned earlier the necessity of this method is that all the elements should
be sorted. So let us take an arry of sorted elements.

Step 1: Now the key element which is to be searched is = 99 key = 99.

Step 2: Find the middle element of the array. Compare it with the key

if middle < key

i.e. if 42 < 99

if 42 < 99 search the sublist 2.


Here middle element is 99 and key is also 99. Hence we declare that the element
is found and it is at index 6.

You might also like