Tuesday, 12 August 2025

Python Coding challenge - Day 664| What is the output of the following Python Code?

 



Code Explanation:

1. Importing the NumPy Library
import numpy as np
Loads the NumPy library into the program.

The alias np is used so you can type np instead of numpy for every function call.

2. Creating a NumPy Array
arr = np.array([1, 2, 3, 4, 5])
Creates a NumPy array named arr containing integers [1, 2, 3, 4, 5].

NumPy arrays store elements of the same type and support vectorized operations (fast element-wise math).

3. Making a Boolean Mask
mask = arr <= 3
Checks, for each element in arr, if it is less than or equal to 3.

Returns a Boolean array:

[ True, True, True, False, False ]
True means the element satisfies the condition (<= 3).

4. Selecting & Modifying Elements with the Mask
arr[mask] = arr[mask] ** 2
arr[mask] selects only the elements where mask is True: [1, 2, 3].

arr[mask] ** 2 squares each selected element → [1, 4, 9].

Assigns these squared values back into their original positions in arr.

Now arr becomes:
[1, 4, 9, 4, 5]

5. Accessing the Second-to-Last Element
print(arr[-2])
arr[-2] means second from the end (negative indexing starts from the right).

In [1, 4, 9, 4, 5], the second-to-last element is 4.

Prints:
4

Final Output:
4

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (150) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (216) Data Strucures (13) Deep Learning (67) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (185) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1215) Python Coding Challenge (882) Python Quiz (341) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)