In this simple python program, we have to print the odd elements of an array. It's a list-based python program.
To understand this example, you should have knowledge of the following Python programming topics:
This python program is based on arrays. An array is a set of elements of the same data type, which is accessed by a common variable index. In this python program example, we need to print the element which is present in an odd position. In an array, the elements are stored in position starting from 1 and the index from 0. which means when we use array we will get the value from the array first position.
This python program using a for loop starting from position zero to the length of the array incrementing by two in each iteration. So in the first iteration, we get the array which is position 1 and then we get array which is position 3 like that we get the odd position elements.
For example, consider an array of 1 2 3 4 5, then in the first iteration, we get 1 which is in position 1 but the index array. In the second iteration, we get value 3 which is in position 3 but the index array and so on.
STEP 1: Initialize the array O and enter some predefined elements in it.
STEP 2: Use a print statement in python language to print " the odd elements of the array is".
STEP 3: Use a
for loop from zero to length of the array incrementing by 2. which will print the first elements as O which is in position 1, and then print the array O which is in position 3.
STEP 4: Print the result of the odd elements array using print in the python programming language.
arr = [1, 2, 3, 4, 5]; print("Array elements in odd position : "); for i in range(0, len(arr), 2): print(arr[i]);
Elements in the odd position: 1 3 5