Python program to create 1D array of elements and find odd/even numbers
1D(single Dimensional) array is a collection of similar elements. Let us create a 1D array of elements in python as follows….
Creation of 1D array from 1 to 20:
- This program starts from import the built-in file “numpy” and create an object for numpy as np.
- Create an array as s_arr. Using the function “arange()” to assign the size.
- Here, we set the range as 20 members.
- Finally, print the array elements using print() function.
Python Code:
import numpy as np
# Create a 1D(single dimensional) array from 1 to 20
s_arr = np.arange(1, 21)
print("Here is the 1D Array:\n", s_arr)
Output:
Here is the 1D Array:
[ 1 2
3 4 5 6 7
8 9 10 11 12 13 14 15 16 17 18 19
20]
Print Even numbers in the array:
This
program imports the numpy, the built-in file. It creates the object for numpy.
- First, create an array with 20 data members. To create the even_numbers,just use the % operator.
- Find the array elements with even numbers. Print the original array and even_numbers array.
Python Code:
import numpy as np
# Create a single dimensional array from 1 to 20
s_arr = np.arange(1, 21)
#let us find the even numbers
even_numbers = s_arr[s_arr % 2 == 0]
print("Original Array:\n", s_arr)
print("Even Numbers:\n", even_numbers)
Output:
Original Array:
[ 1 2
3 4 5 6 7
8 9 10 11 12 13 14 15 16 17 18 19
20]
Even Numbers:
[ 2 4
6 8 10 12 14 16 18 20]
Print the Odd numbers in the array:
Import the
built-in file numpy and make the object. As usual, create an array.
- Divide the array element by 2. If it is not equal to zero, then it is an odd number. Make a list of it.
- At last, print the original array and the array with odd numbers.
Python code:
import numpy as np
# Create a 1D array from 1 to 20
s_arr = np.arange(1, 21)
#Find the odd numbers
odd_numbers = s_arr[s_arr % 2 != 0]
print("Original Array is:\n", s_arr)
print("Odd Numbers:\n", odd_numbers)
Output:
Original Array is:
[ 1 2
3 4 5 6 7
8 9 10 11 12 13 14 15 16 17 18 19
20]
Odd Numbers:
[ 1 3
5 7 9 11 13 15 17 19]
These are the ways to create an array of elements and find
the odd numbers and even numbers was done successfully. Keep Coding!!!
Comments
Post a Comment