Python Program to Print All Odd Indexed Elements of a List
Let's take a variable length to store the sizer list and ask a user to enter list length.
Then take an empty list and use the for loop to iterate from 0 to list length and accept the list of numbers from the user using input function call and append it to the numbers list.
length = int(input("Enter List Length : "))
numbers_list = []
for _ in range(length):
temp = int(input("Enter List Element : "))
numbers_list.append(temp)
Then print a user-friendly message that is all odd index elements are
print("All Odd Indexed Elements are ...")
Now using a for loop Enumerate the list of numbers to get the index as well as item. using if statement check if index is odd using the modulus by 2. check if the remainder is one if yes print the item because it is referred to as an odd indexed element.
for index, item in enumerate(numbers_list):
if index % 2 == 1:
print(item, end=" ")
Final program
=================
length = int(input("Enter List Length : "))
numbers_list = []
for _ in range(length):
temp = int(input("Enter List Element : "))
numbers_list.append(temp)
print("All Odd Indexed Elements are ...")
for index, item in enumerate(numbers_list):
if index % 2 == 1:
print(item, end=" ")
Output
================
Enter List Length : 6
Enter List Element : 11
Enter List Element : 56
Enter List Element : 90
Enter List Element : 67
Enter List Element : 99
Enter List Element : 60
All Odd Indexed Elements are ...
56 67 60
The program can also be returned for the list of Strings just remove the integer type conversion can change the list variable to string list
Final program
=========================
length = int(input("Enter List Length : "))
string_list = []
for _ in range(length):
temp = int(input("Enter List Element : "))
string_list.append(temp)
print("All Odd Indexed Elements are ...")
for index, item in enumerate(string_list):
if index % 2 == 1:
print(item, end=" ")
Output
================
Enter List Length : 5
Enter List Element : hello
Enter List Element : how
Enter List Element : are
Enter List Element : you
Enter List Element : ???
All Odd Indexed Elements are ...
how you
Conclusion
===================
Try the program for the floating point values and comment down below if you have any queries
0 Comments