Array and Its Operations
DIFFERENT OPERATIONS IN ARRAYS :
1. append( )-Adds an element at the end of the list
2. clear( )-Removes all the elements from the list.
3. copy( )-Returns a copy of the list.
4. count( )-Returns the number of elements with the specified value.
5. extend( )-Adds the element to the end of the current list.
6. index( )-Returns the index of the first element with the specified value.
7. insert( )-Adds an element at the specified position.
8. pop( )-Removes the element at the specified position.
9. remove( )-Removes the first item with the specified value.
[Link]( )-Reverses the order of the list.
[Link]( )-Sorts the lists.
HANDLING STRINGS AND CHARACTERS
• WHAT IS A STRING ?
A string is a sequence of characters enclosed in either single quotes ‘.’ or double quotes “.”. It is
used for representing textual data.
CREATING A STRING:
Strings can be created using either single quotes or double quotes.
For Example- s1=‘VSSUT BURLA’
s2=“VSSUT BURLA”
Multi-line Strings: If we need to span multiple lines then we can use triple quotes.
For Examples: s= “ “ “ I am learning
coding from youtube ” ” ”
OPERATIONS IN STRING:
• Let us consider a string s=“HELLO”
• Access Characters: s[0] gives ‘H’.
• String Slicing: s[1:4] gives ‘ell’.
• Concatenation: “Hi” + “there” gives “Hi there”.
• METHODS: We have a string s,
• [Link]( )- Converts to uppercase.
• [Link]( )- Converts to lowercase
• [Link](“ ”)- Spilts by spaces into a list.
• “ ”.join([‘Hi’, ‘there’])- Joins list into a string.
An array is a special variable, which can hold more than one value at a time.
Python does not have built-in support for Arrays.
1. Array using list (most common)
Lists in Python are the most flexible and commonly used data structure for sequential storage. They
are similar to arrays in other languages but with several key differences:
• Dynamic Typing: Python lists can hold elements of different types in the same list.
• Dynamic Resizing: Lists are dynamically resized, meaning you can add or remove elements
without declaring the size of the list upfront.
• Built-in Methods: Python lists come with numerous built-in methods that allow for easy
manipulation of the elements within them, including methods for appending, removing, sorting and
reversing
• Creating an array (list)
arr = [10, 20, 30, 40] • Deletion
[Link](20) # removes value
[Link]() # removes last element
• Accessing elements [Link](1) # removes element at index 1
arr[0] # 10
• Updating elements
arr[-1] # 40 arr[1] = 22
• Searching
• Traversing an array if 30 in arr:
for x in arr: print("Found")
print(x)
• Length of array
len(arr)
• Insertion
[Link](50) # add at end • Sorting
[Link]() # ascending
[Link](2, 25) # add at index 2
[Link](reverse=True) # descending
• List slicing:
Slicing allows you to extract a portion of a list using [start:stop:step]:
Example:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[::2]) # [10, 30, 50]
• List Bound (Indexing & Negative Index)
Access elements using indices: list[index]
Supports negative indexing (from the end):
Ex:
items = ['a', 'b', 'c', 'd']
print(items[0]) # 'a'
print(items[-1]) # 'd'
• Cloning a List
original = [1, 2, 3]
# Using slicing
clone1 = original[:]
# Using list() constructor
clone2 = list(original)
# Using copy() method
clone3 = [Link]()
Output:
Clone1 (slicing): [1, 2, 3]
Clone2 (list()): [1, 2, 3]
Clone3 (copy()): [1, 2, 3]
• Mutability in List
A list in Python is mutable, which means you can modify its elements, add new items,
or remove items without creating a new list.
(a) sort()
• Sorts the list in place (alters original list).
Example:
numbers = [3, 1, 4, 2]
[Link]()
print(numbers) # [1, 2, 3, 4]
(b)reverse() (d)clear()
Reverses the elements of the list in place. Removes all elements from the list.
Example: fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4] [Link]()
[Link]() print(fruits) # []
print(numbers) # [4, 3, 2, 1] (e)pop()
(c)remove() Removes and returns element at a given index
(default is last).
Removes the first occurrence of a specified value.
Ex:
Example:
fruits = ['apple', 'banana', 'cherry', 'banana'] numbers = [10, 20, 30, 40]
x = [Link]()
[Link]('banana')
print(x) # 40
print(fruits) # ['apple', 'cherry', 'banana']
print(numbers) # [10, 20, 30]
y = [Link](1)
print(y) # 20
print(numbers) # [10, 30]
Functional Operations: Map & Filter b. filter()
a. map()
Keeps elements that satisfy a condition.
Applies a function to each element of a list.
Example: Example:
nums = [1, 2, 3, 4] nums = [1, 2, 3, 4, 5, 6]
squared = list(map(lambda x: x**2, nums)) even_nums = list(filter(lambda x: x % 2 == 0,
print(squared) # [1, 4, 9, 16] nums))
Explanation:
print(even_nums) # [2, 4, 6]
map(lambda x: x**2, nums)
A lambda function is a small anonymous function in Python. Explanation:
map() applies a function to each element of an iterable (like filter() takes a function and an iterable
a list). (here, nums).
The function here is a lambda function: lambda x: x**2
It keeps only the elements where the
This means: for any input x, return x squared.
function returns True.
map() returns a map object (an iterator), not a list yet.
Write a Python program to store student marks in an array and find the total, average, highest, and
lowest marks.
marks = [] Output:
n = int(input("Enter number of students: ")) Enter number of students: 5
for i in range(n): Enter marks of student 1: 78
m = int(input(f"Enter marks of student {i+1}: ")) Enter marks of student 2: 85
[Link](m) Enter marks of student 3: 90
total = sum(marks) Enter marks of student 4: 72
average = total / n Enter marks of student 5: 88
print("\nMarks:", marks)
Marks: [78, 85, 90, 72, 88]
print("Total Marks:", total)
Total Marks: 413
print("Average Marks:", average)
Average Marks: 82.6
print("Highest Marks:", max(marks))
Highest Marks: 90
print("Lowest Marks:", min(marks))
Lowest Marks: 72
Write a Python program to reverse an array using a list.
# Reverse an array using list
arr = []
n = int(input("Enter number of elements: "))
for i in range(n):
[Link](int(input(f"Enter element {i+1}: ")))
print("\nOriginal Array:", arr)
[Link]()
print("Reversed Array:", arr)
Count Even and Odd Numbers
arr = []
n = int(input("Enter number of elements: "))
for i in range(n):
[Link](int(input(f"Enter element {i+1}: ")))
even = 0
odd = 0
for num in arr:
if num % 2 == 0:
even += 1
else:
odd += 1
print("\nArray:", arr)
print("Even numbers:", even)
print("Odd numbers:", odd)
2. Array using array module (for same-type elements)
Unlike Python lists (can store elements of mixed types), arrays must have all elements of same
type.
Having only homogeneous elements makes it memory-efficient.
import array as arr # imports the array module and arr is alias
a = [Link]('i', [1, 2, 3, 4]) # Creates an array named a and 'i' indicates the type code for integers
Operations
• [Link](5)
• [Link](1, 10)
• [Link]()
• [Link](3)
• Python Array Type codes table
3. Array using NumPy (for numerical computing):ndarray
A NumPy array is a multidimensional, homogeneous array provided by the NumPy library in Python.
Homogeneous: All elements must be of the same data type (e.g., all integers, all floats).
Efficient: Supports fast operations, broadcasting, and vectorized computations.
Multidimensional: Can be 1D, 2D, 3D, or higher.
Supports vectorized operations: You can do math on all elements without loops.
Best for math, data science, and ML.
import numpy as np
Example:Create an array of 5 integers and display it
import numpy as np
a = [Link]([1, 2, 3, 4,5])
print(a)
Explanation:
• [Link]() creates a NumPy array (ndarray) from the Python list [1, 2, 3, 4, 5].
• Key points about this array:
• Homogeneous: All elements are of the same type (int here).
• 1D Array: This is a one-dimensional array.
Example Comparison between Python list and NumPy array
• Python list: • NumPy array:
Example: Example:
lst = [1, 2, 3] import numpy as np
print(lst * 2) # [1, 2, 3, 1, 2, 3] (repeats the arr = [Link]([1, 2, 3])
list) print(arr * 2) # [2 4 6] (element-wise
multiplication)
For elementwise multiplication:
lst = [1, 2, 3]
result = [x * 2 for x in lst]
print(result) # [2, 4, 6]
Example: Create 2D Array & Access Elements (User Input)
import numpy as np # Access element
# Get number of rows and columns r = int(input("\nEnter row index to access: "))
rows = int(input("Enter number of rows: ")) c = int(input("Enter column index to access: "))
cols = int(input("Enter number of columns: ")) print(f"Element at position [{r}][{c}] is:", array[r][c])
# Create empty list to store all rows O/P:
Enter number of rows: 2
elements = []
Enter number of columns: 3
print("Enter the elements row by row:")
Enter the elements row by row:
for i in range(rows):
Element [0][0]: 1
row = []# to store every row
Element [0][1]: 2
for j in range(cols):
Element [0][2]: 3
value = int(input(f"Element [{i}][{j}]: "))
Element [1][0]: 4
[Link](value)
Element [1][1]: 5
[Link](row)
Element [1][2]: 6
# Converts the list of lists (elements) into a NumPy 2D array.
2D Array:
array = [Link](elements)
[[1 2 3]
[4 5 6]]
print("\n2D Array:") Enter row index to access: 1
print(array) Enter column index to access: 2
Element at position [1][2] is: 6
OR
import numpy as np
r = int(input("Rows: "))
c = int(input("Columns: "))
a = [Link]([[int(input()) for j in range(c)] for i in range(r)])
print(a)
i = int(input("Row index: "))
j = int(input("Column index: "))
print("Element:", a[i][j])
Handling Strings and Characters
In Python, a string is a sequence of characters written inside quotes. It can include letters, numbers, symbols,
and spaces.
Python does not have a separate character type.
A single character is treated as a string of length one.
Strings are commonly used for text handling and manipulation.
Creating a String
Strings can be created using either single ('...') or double ("...") quotes. Both behave the same.
Ex:
s1 = 'VSSUT' # single quote
s2 = "VSSUT" # double quote
print(s1)
print(s2)
Multi-line Strings Accessing characters in String
Use triple quotes ('''...''' ) or ( """...""") for strings that Strings are indexed sequences. Positive indices start
span multiple lines. at 0 from the left; negative indices start at -1 from the
Newlines are preserved. right .
Ex: String Slicing
s = """I am Learning Slicing is a way to extract a portion of a string by
specifying the start and end indexes.
Python String """
Ex:
print(s)
s = "Hello, Python!"
O/P:
print(s[0:5])
I am Learning
O/P:
Python String
Output
Hello
Extract Characters Using Negative Indices
Example:
s = "abcdefghijklmno"
print(s[-4:])
print(s[:-3])
print(s[-5:-2])
print(s[-8:-1:2])
O/P:
lmno
abcdefghijkl
klm
hjln