w3resource

NumPy: Create a vector with values ​​ranging from 15 to 55 and print all values ​​except the first and last

NumPy: Basic Exercise-19 with Solution

Write a NumPy program to create a vector with values ​​ranging from 15 to 55 and print all values ​​except the first and last.

This NumPy program creates a vector with values ranging from 15 to 55. It then prints all elements of the vector except the first and last ones. By utilizing NumPy's array slicing capabilities, the program efficiently extracts and displays the specified subset of the vector's elements.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'v' containing integers from 15 to 54 using np.arange()
v = np.arange(15, 55)

# Printing a message indicating the original vector 'v'
print("Original vector:")
print(v)

# Printing a message indicating all values of the vector 'v' except the first and last elements using slicing [1:-1]
print("All values except the first and last of the said vector:")
print(v[1:-1]) 

Output:

Original vector:
[15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54]
All values except the first and last of the said vector:
[16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 41 42 43 44 45 46 47 48 49 50 51 52 53]                         

Explanation:

In above code the np.arange() function creates a NumPy array containing values within a specified interval. In this case, it generates an array starting at 15 and ending before 55, with a default step size of 1. This results in an array of integers from 15 to 54.

The print(v[1:-1]) function prints a slice of the array 'v' to the console, starting from the second element (index 1) and ending before the last element (index -1). In Python, negative indices count from the end of the array. The slice v[1:-1] will exclude the first and last elements of the original array, resulting in an output of integers from 16 to 53.

Python-Numpy Code Editor:

Previous: NumPy program to generate an array of 15 random numbers from a standard normal distribution.
Next: NumPy program to create a 3X4 array using and iterate over it.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/basic/numpy-basic-exercise-19.php