Skip to main content

Set A - Question 1

1. a) Consider the following NumPy array:

import numpy as np
values = np.array([10, 20, 30, 40, 50])

Demonstrate the following array operations: i. Access the first, fourth, and last elements using indexing. ii. Extract the first four elements using slicing. iii. Replace the value 20 with 100. iv. Create a new array by multiplying all values by 3. v. Explain the role of indexing and slicing in NumPy arrays.

Answer

i. Access the first, fourth, and last elements using indexing

import numpy as np
values = np.array([10, 20, 30, 40, 50])

# Accessing elements using 0-based and negative indexing
first = values[0] # 10
fourth = values[3] # 40
last = values[-1] # 50

print("First:", first, "Fourth:", fourth, "Last:", last)

ii. Extract the first four elements using slicing

# Slicing from index 0 to 4 (exclusive)
first_four = values[:4] # array([10, 20, 30, 40])
print("First four elements:", first_four)

iii. Replace the value 20 with 100

# Replacing the element at index 1 (value 20) in-place
values[1] = 100
print("Modified array:", values) # array([10, 100, 30, 40, 50])

iv. Create a new array by multiplying all values by 3

# Vectorized element-wise scalar multiplication
multiplied_values = values * 3
print("New array multiplied by 3:", multiplied_values) # array([30, 300, 90, 120, 150])

v. Explain the role of indexing and slicing in NumPy arrays

  • Indexing: Allows direct access and modification of specific elements in an array instantly using their coordinates, bypassing slower sequential loop runs.
  • Slicing: Enables selecting a contiguous portion or subset of data (views) without duplicating the data in memory. This is highly memory-efficient for large datasets.

1. b) Consider the following Python collections:

list1 tuple1 set1 Answer the following: i. Differentiate lists, tuples, and sets with respect to ordering and mutability. ii. Explain how duplicate elements are treated in each collection. iii. Demonstrate how an element can be accessed from the list and tuple. iv. Perform an update operation on the list and explain why the same operation cannot be performed directly on the tuple. v. Explain why indexing cannot be used to retrieve a specific element from a set.

Answer

i. Differentiate lists, tuples, and sets with respect to ordering and mutability

CollectionOrderingMutabilityExplanation
ListOrderedMutablePreserves insertion order; elements can be modified, added, or deleted in-place.
TupleOrderedImmutablePreserves insertion order; elements cannot be changed or resized after creation.
SetUnorderedMutableDoes not preserve any order; elements can be added/removed, but must be unique and hashable.

ii. Explain how duplicate elements are treated in each collection

  • List: Allows duplicate elements; each duplicate gets its own unique index position.
  • Tuple: Allows duplicate elements; duplicates are preserved and treated as separate items.
  • Set: Disallows duplicate elements; duplicates are automatically discarded during insertion to ensure strict uniqueness.

iii. Demonstrate how an element can be accessed from the list and tuple

# Initializing collections
list1 = ["Apple", "Banana", "Cherry"]
tuple1 = (10, 20, 30)

# Accessing elements using 0-based indexing
list_element = list1[1] # Returns "Banana"
tuple_element = tuple1[2] # Returns 30

iv. Perform an update operation on the list and explain why the same operation cannot be performed directly on the tuple

# Updating list element (allowed since lists are mutable)
list1[1] = "Mango"

# Attempting to update tuple element raises a TypeError
try:
tuple1[1] = 99
except TypeError as e:
print("Tuple modification error:", e) # 'tuple' object does not support item assignment

Why the same operation cannot be performed directly on the tuple:

  • Immutable Memory Layout: Tuples are allocated in a contiguous, read-only memory space during creation. Once built, their elements and length cannot change.
  • No Mutator Interface: The tuple data structure does not implement write-access methods (__setitem__ is omitted).

v. Explain why indexing cannot be used to retrieve a specific element from a set

  • Unordered Nature: Sets are implemented as hash tables and do not maintain any predictable sequence or order of elements.
  • No Index Interface: Since elements do not have indices, sets do not support subscripting (TypeError: 'set' object is not subscriptable). Elements can only be accessed by iterating or using membership tests (in).

1. c) What are Python libraries, and why are they important in programming? Discuss the role of at least three commonly used libraries in data analysis, highlighting their key features and applications.

Answer

Definition of Python Libraries

A Python library is a collection of pre-written modules, packages, and functions that developers can import to perform standard or complex operations without writing code from scratch.

Why they are important:

  • Code Reusability & Speed: Eliminates "reinventing the wheel," dramatically accelerating development.
  • High Performance: Core scientific libraries (e.g., NumPy) are written in compiled languages like C, rendering operations vastly faster than raw Python.
  • Community Testing: Open-source, highly tested modules ensure fewer bugs, stability, and high security.

Role, Key Features, and Applications of Three Key Data Analysis Libraries

  1. NumPy (Numerical Python)

    • Role: Foundational library for scientific computing and high-speed numerical processing.
    • Key Features: Multi-dimensional array object (ndarray), vectorized operations (loopless math), linear algebra support.
    • Applications: Vector algebra, fast arithmetic, image manipulation, and serving as the engine for Pandas/Scikit-Learn.
  2. Pandas

    • Role: Structured data manipulation and tabular analysis.
    • Key Features: DataFrame (2D tables) and Series (1D arrays) objects, extensive handlers for missing data, robust merging/joining, and group-by aggregations.
    • Applications: Data cleaning (ETL), handling tabular files (CSVs, Excel files), querying, and time-series data analysis.
  3. Matplotlib

    • Role: Complete plotting and data visualization.
    • Key Features: Extensive styling (fonts, grid, colors), subplots management, and multi-format exports.
    • Applications: Visualizing distributions, scatter trend lines, and reporting metrics during exploratory analysis.