Experiment 2
Experiment 2
Students Work
A] Defining Lists, Accessing Values in List, Deleting Values in List, Updating Lists
# Defining a list
fruits[1] = "grape"
# Adding an element
fruits.append("orange")
fruits.insert(1, "kiwi")
# Removing an element
fruits.remove("banana")
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(max(numbers)) # Output: 5
print(min(numbers)) # Output: 1
print(sum(numbers)) # Output: 15
numbers.sort()
Tuples
# Defining a tuple
coordinates = (4, 5, 6)
print(coordinates[1]) # Output: 5
# Tuples are immutable, so we cannot delete or update individual elements.
del coordinates
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Repeating a tuple
repeat_tuple = tuple1 * 2
tup = (1, 2, 3, 4, 5)
print(tup.count(3)) # Output: 1
print(tup.index(4)) # Output: 3
Dictionaries
a) Accessing Values in Dictionary, Deleting Values in Dictionary, Updating Dictionary
# Defining a dictionary
# Deleting a value
del student["age"]
# Updating a value
student["course"] = "Physics"
student["grade"] = "A"
print(student) # Output: {'name': 'John', 'age': 22, 'course': 'Math', 'grade': 'A'}
# Copying a dictionary
new_student = student.copy()
print(new_student) # Output: {'name': 'John', 'age': 22, 'course': 'Math', 'grade': 'A'}
# Clearing a dictionary
student.clear()
print(student) # Output: {}
Sets
# Defining a set
colors.remove("blue")
colors.add("yellow")
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union of sets
# Intersection of sets
# Difference of sets
print(len(colors)) # Output: 3
Strings
a) String Initialization, Indexing, Slicing, Concatenation, Membership & Immutability
# String initialization
# Indexing a string
print(greeting[0]) # Output: H
# Slicing a string
# String concatenation
# Membership check
# Converting to uppercase
print(text.upper()) # Output: 'HELLO WORLD!'
# Converting to lowercase
# Splitting a string
words = text.split()
# Replacing a substring
import numpy as np
print(arr[1]) # Output: 2
print(arr[1:4]) # Output: [2 3 4]
# Aggregate functions
# Addition
result_add = matrix1 + matrix2
print("Addition:")
print(result_add)
# Subtraction
result_sub = matrix1 - matrix2
print("\nSubtraction:")
print(result_sub)
# Multiplication (Element-wise)
result_mul = matrix1 * matrix2
print("\nMultiplication (Element-wise):")
print(result_mul)
# Division (Element-wise)
result_div = matrix1 / matrix2
print("\nDivision (Element-wise):")
print(result_div)
Addition:
[[ 6 8]
[10 12]]
Subtraction:
[[-4 -4]
[-4 -4]]
Multiplication (Element-wise):
[[ 5 12]
[21 32]]
Division (Element-wise):
[[0.2 0.33333333]
[0.42857143 0.5 ]]
2. Matrix Operations
NumPy also provides matrix operations such as dot product and matrix multiplication.
a) Dot Product
The dot product of two matrices can be calculated using np.dot() or @ operator:
output:
Dot Product:
[[19 22]
[43 50]]
transpose_matrix1 = matrix1.T
print("\nTranspose of matrix1:")
print(transpose_matrix1)
output
Transpose of matrix1:
[[1 3]
[2 4]]
c) Matrix Inversion
Inverting a matrix (if it's square and non-singular) can be done using np.linalg.inv():
output:
Inverse of matrix1:
[[-2. 1. ]
[ 1.5 -0.5]]
3. Aggregate Functions
output:
Sum of all elements in matrix1:
10
Defining a Function
Functions in Python are defined using the def keyword. You can also pass parameters to
functions and return values from them.
You can return values from a function using the return keyword.
You can pass different types of parameters to a function (positional, keyword, and default
parameters).
# Positional Parameters
def multiply(a, b):
return a * b
Nested Functions
A nested function is a function defined inside another function. Nested functions can access
variables from the outer function.
# Outer function
def outer():
x = 5 # Local variable of the outer function
# Nested function
def inner():
print(f"Inner function: x = {x}") # Accessing variable from outer function
Recursive Functions
A recursive function is one that calls itself. It is often used for tasks that can be broken down into
smaller, similar tasks, like calculating factorials.
Lambda Functions
A lambda function is an anonymous function defined using the lambda keyword. It is often used
for simple, short functions.
Map Function
The map() function applies a given function to all items in an iterable (e.g., a list) and returns a
map object (which can be converted to a list).
numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)
numbers = [1, 2, 3, 4]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16]
Filter Function
The filter() function filters items in an iterable based on a condition provided by a function. It
returns an iterator of the items that satisfy the condition.
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)