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

Experiment 2

The document provides an overview of advanced data types and functions in Python, including lists, tuples, dictionaries, sets, strings, and arrays using NumPy. It covers defining, accessing, updating, and deleting elements, as well as built-in functions and basic operations for each data type. Additionally, it introduces functions, including defining, calling, returning values, and using lambda functions, map, reduce, and filter.

Uploaded by

pubg2152005
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)
1 views

Experiment 2

The document provides an overview of advanced data types and functions in Python, including lists, tuples, dictionaries, sets, strings, and arrays using NumPy. It covers defining, accessing, updating, and deleting elements, as well as built-in functions and basic operations for each data type. Additionally, it introduces functions, including defining, calling, returning values, and using lambda functions, map, reduce, and filter.

Uploaded by

pubg2152005
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/ 17

Experiment 2: Advanced data types & Functions

Students Work
A] Defining Lists, Accessing Values in List, Deleting Values in List, Updating Lists

# Defining a list

fruits = ["apple", "banana", "cherry"]

# Accessing values in a list

print(fruits[0]) # Output: apple

# Deleting values in a list

del fruits[1] # Removes "banana"

print(fruits) # Output: ['apple', 'cherry']

# Updating values in a list

fruits[1] = "grape"

print(fruits) # Output: ['apple', 'grape']

b) Basic List Operations

fruits = ["apple", "banana", "cherry"]

# Adding an element

fruits.append("orange")

print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']

# Inserting an element at a specific position

fruits.insert(1, "kiwi")

print(fruits) # Output: ['apple', 'kiwi', 'banana', 'cherry', 'orange']

# Removing an element
fruits.remove("banana")

print(fruits) # Output: ['apple', 'kiwi', 'cherry', 'orange']

c) Built-in List Functions

numbers = [1, 2, 3, 4, 5]

# Finding length of the list

print(len(numbers)) # Output: 5

# Finding maximum value in the list

print(max(numbers)) # Output: 5

# Finding minimum value in the list

print(min(numbers)) # Output: 1

# Summing up all elements in the list

print(sum(numbers)) # Output: 15

# Sorting the list

numbers.sort()

print(numbers) # Output: [1, 2, 3, 4, 5]

Tuples

a) Accessing Values in Tuples, Deleting Values in Tuples, Updating Tuples

# Defining a tuple

coordinates = (4, 5, 6)

# Accessing values in a tuple

print(coordinates[1]) # Output: 5
# Tuples are immutable, so we cannot delete or update individual elements.

# However, you can create a new tuple.

# Deleting an entire tuple:

del coordinates

# print(coordinates) # This will raise an error since the tuple is deleted.

b) Basic Tuple Operations

# Concatenating two tuples

tuple1 = (1, 2, 3)

tuple2 = (4, 5, 6)

result = tuple1 + tuple2

print(result) # Output: (1, 2, 3, 4, 5, 6)

# Repeating a tuple

repeat_tuple = tuple1 * 2

print(repeat_tuple) # Output: (1, 2, 3, 1, 2, 3)

c) Built-in Tuple Functions

tup = (1, 2, 3, 4, 5)

# Finding the count of a value in the tuple

print(tup.count(3)) # Output: 1

# Finding the index of a value in the tuple

print(tup.index(4)) # Output: 3

Dictionaries
a) Accessing Values in Dictionary, Deleting Values in Dictionary, Updating Dictionary

# Defining a dictionary

student = {"name": "John", "age": 22, "course": "Math"}

# Accessing values in a dictionary

print(student["name"]) # Output: John

# Deleting a value

del student["age"]

print(student) # Output: {'name': 'John', 'course': 'Math'}

# Updating a value

student["course"] = "Physics"

print(student) # Output: {'name': 'John', 'course': 'Physics'}

b) Basic Dictionary Operations

student = {"name": "John", "age": 22, "course": "Math"}

# Adding a new key-value pair

student["grade"] = "A"

print(student) # Output: {'name': 'John', 'age': 22, 'course': 'Math', 'grade': 'A'}

# Checking if a key exists

print("age" in student) # Output: True

# Getting keys, values, and items

print(student.keys()) # Output: dict_keys(['name', 'age', 'course', 'grade'])

print(student.values()) # Output: dict_values(['John', 22, 'Math', 'A'])


print(student.items()) # Output: dict_items([('name', 'John'), ('age', 22), ('course', 'Math'), ('grade', 'A')])

c) Built-in Dictionary Functions

# 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

a) Accessing Values in Set, Deleting Values in Set, Updating Sets

# Defining a set

colors = {"red", "blue", "green"}

# Accessing values in a set (Sets do not support indexing)

for color in colors:

print(color) # Outputs all elements in the set

# Deleting a value from a set

colors.remove("blue")

print(colors) # Output: {'red', 'green'}

# Adding a value to a set

colors.add("yellow")

print(colors) # Output: {'red', 'green', 'yellow'}


b) Basic Set Operations

set1 = {1, 2, 3}

set2 = {3, 4, 5}

# Union of sets

print(set1 | set2) # Output: {1, 2, 3, 4, 5}

# Intersection of sets

print(set1 & set2) # Output: {3}

# Difference of sets

print(set1 - set2) # Output: {1, 2}

# Symmetric difference of sets

print(set1 ^ set2) # Output: {1, 2, 4, 5}

c) Built-in Set Functions

# Length of the set

print(len(colors)) # Output: 3

# Checking if a set is a subset of another

print({1, 2}.issubset(set1)) # Output: True

# Checking if a set is a superset of another

print(set1.issuperset({1, 2})) # Output: True

Strings
a) String Initialization, Indexing, Slicing, Concatenation, Membership & Immutability

# String initialization

greeting = "Hello, world!"

# Indexing a string

print(greeting[0]) # Output: H

# Slicing a string

print(greeting[0:5]) # Output: Hello

# String concatenation

greeting2 = " How are you?"

full_greeting = greeting + greeting2

print(full_greeting) # Output: Hello, world! How are you?

# Membership check

print("world" in greeting) # Output: True

# Immutability (You cannot change a string directly)

# greeting[0] = 'h' # This will raise an error

b) Built-in String Functions

text = " Hello World! "

# Removing leading and trailing spaces

print(text.strip()) # Output: 'Hello World!'

# Converting to uppercase
print(text.upper()) # Output: 'HELLO WORLD!'

# Converting to lowercase

print(text.lower()) # Output: 'hello world!'

# Splitting a string

words = text.split()

print(words) # Output: ['Hello', 'World!']

# Replacing a substring

print(text.replace("World", "Python")) # Output: ' Hello Python! '

Arrays (Using NumPy for Multi-dimensional Arrays)

a) Working with Single-dimensional Arrays

import numpy as np

# Creating a single-dimensional array

arr = np.array([1, 2, 3, 4, 5])

# Indexing and slicing

print(arr[1]) # Output: 2

print(arr[1:4]) # Output: [2 3 4]

b) Working with Multi-dimensional Arrays

# Creating a 2D array (Matrix)

matrix = np.array([[1, 2], [3, 4], [5, 6]])


# Matrix operations

print(matrix + 10) # Adding 10 to each element

print(matrix * 2) # Multiplying each element by 2

# Aggregate functions

print(np.sum(matrix)) # Output: 21 (sum of all elements)

print(np.mean(matrix)) # Output: 3.5 (mean of all elements)

1. Mathematical Operations on Multi-dimensional Arrays


# Creating two 2D arrays (matrices)
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# 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:

# Dot product of matrix1 and matrix2


dot_product = np.dot(matrix1, matrix2)
print("\nDot Product:")
print(dot_product)

# Alternatively, using the @ operator


dot_product_alt = matrix1 @ matrix2
print("\nDot Product (using @ operator):")
print(dot_product_alt)

output:
Dot Product:
[[19 22]
[43 50]]

Dot Product (using @ operator):


[[19 22]
[43 50]]
b) Matrix Transpose

Transpose of a matrix flips it over its diagonal:

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():

# Inversion of matrix1 (if it is invertible)


matrix_inv = np.linalg.inv(matrix1)
print("\nInverse of matrix1:")
print(matrix_inv)

output:
Inverse of matrix1:
[[-2. 1. ]
[ 1.5 -0.5]]

3. Aggregate Functions

NumPy provides several aggregate functions to compute statistics across arrays:

# Sum of all elements in the matrix


sum_matrix1 = np.sum(matrix1)
print("\nSum of all elements in matrix1:")
print(sum_matrix1)

# Mean of all elements in the matrix


mean_matrix1 = np.mean(matrix1)
print("\nMean of all elements in matrix1:")
print(mean_matrix1)
# Maximum and minimum elements in the matrix
max_element = np.max(matrix1)
min_element = np.min(matrix1)
print("\nMaximum element in matrix1:", max_element)
print("Minimum element in matrix1:", min_element)

# Axis-wise operations (for rows or columns)


sum_axis0 = np.sum(matrix1, axis=0) # Sum along columns
sum_axis1 = np.sum(matrix1, axis=1) # Sum along rows

print("\nSum along columns (axis=0):")


print(sum_axis0)

print("\nSum along rows (axis=1):")


print(sum_axis1)

output:
Sum of all elements in matrix1:
10

Mean of all elements in matrix1:


2.5

Maximum element in matrix1: 4


Minimum element in matrix1: 1

Sum along columns (axis=0):


[4 6]

Sum along rows (axis=1):


[3 7]

a) Built-in Functions in Python


# Using the `len()` function to get the length of an object
text = "Hello, World!"
print(len(text)) # Output: 13

# Using the `max()` function to find the maximum value


numbers = [10, 20, 30, 5]
print(max(numbers)) # Output: 30
# Using the `min()` function to find the minimum value
print(min(numbers)) # Output: 5

# Using the `sum()` function to find the sum of a list


print(sum(numbers)) # Output: 65

# Using the `sorted()` function to sort a list


sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [5, 10, 20, 30]

# Using the `abs()` function to get the absolute value


negative_number = -42
print(abs(negative_number)) # Output: 42

# Using the `round()` function to round a number


float_number = 3.14159
print(round(float_number, 2)) # Output: 3.14

b) Defining Function, Calling Function, Returning Values, Passing Parameters

Defining a Function

Functions in Python are defined using the def keyword. You can also pass parameters to
functions and return values from them.

# Defining a function that takes parameters


def greet(name, age):
return f"Hello, {name}! You are {age} years old."

# Calling the function


greeting = greet("Alice", 25)
print(greeting) # Output: Hello, Alice! You are 25 years old.

# Function with no parameters


def say_hello():
return "Hello, World!"

print(say_hello()) # Output: Hello, World!


Returning Values from a Function

You can return values from a function using the return keyword.

# Function that returns the sum of two numbers


def add_numbers(a, b):
return a + b

result = add_numbers(10, 15)


print(result) # Output: 25

Passing Parameters to Functions

You can pass different types of parameters to a function (positional, keyword, and default
parameters).

# Positional Parameters
def multiply(a, b):
return a * b

print(multiply(3, 4)) # Output: 12

# Keyword Parameters (using parameter names)


def power(base, exponent=2): # Default exponent is 2
return base ** exponent

print(power(3)) # Output: 9 (since default exponent is 2)


print(power(3, 3)) # Output: 27 (explicitly passing exponent)

c) Nested and Recursive Functions

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

inner() # Calling the nested function

outer() # Output: Inner function: x = 5

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.

# Function to calculate factorial using recursion


def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

In the recursive function, the base case (n == 0 or n == 1) prevents infinite recursion.

d) Anonymous Functions (Lambda, Map, Reduce, Filter)

Lambda Functions

A lambda function is an anonymous function defined using the lambda keyword. It is often used
for simple, short functions.

# A simple lambda function to add two numbers


add = lambda x, y: x + y
print(add(10, 5)) # Output: 15

# Lambda function for squaring a number


square = lambda x: x ** 2
print(square(4)) # Output: 16

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).

# Function to square a number


def square(x):
return x ** 2

numbers = [1, 2, 3, 4]
squared_numbers = map(square, numbers)

# Converting map object to a list


print(list(squared_numbers)) # Output: [1, 4, 9, 16]

You can also use a lambda function with map():

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.

# Function to check if a number is even


def is_even(x):
return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)

# Converting filter object to a list


print(list(even_numbers)) # Output: [2, 4, 6]
 Program a] Python Program to Check whether a String is Palindrome or not using
Recursion
B] Python Program to Reverse a String Without using Recursion
 C] Python Program to Create a List of Tuples with the First Element as the Number
and Second Element as the Square of the Number
 D] Python Program to Convert Binary to Gray Code using function

You might also like