Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to print the elements of an array present on odd position
When we need to print elements at odd positions in a Python list, we can use a for loop with the range() function. By starting from index 1 and using a step size of 2, we can access only the odd-positioned elements.
Using range() with Step Size
The most common approach is to iterate through odd indices using range(1, len(list), 2) ?
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is:")
print(my_list)
print("The elements in odd positions are:")
for i in range(1, len(my_list), 2):
print(my_list[i])
The output of the above code is ?
The list is: [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in odd positions are: 42 34 0 1
Using List Slicing
Another approach is to use list slicing with [1::2] to get all odd-positioned elements ?
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is:")
print(my_list)
print("The elements in odd positions are:")
odd_elements = my_list[1::2]
for element in odd_elements:
print(element)
The list is: [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in odd positions are: 42 34 0 1
Using enumerate()
We can also use enumerate() to get both index and value, then check if the index is odd ?
my_list = [31, 42, 13, 34, 85, 0, 99, 1, 3]
print("The list is:")
print(my_list)
print("The elements in odd positions are:")
for index, element in enumerate(my_list):
if index % 2 == 1:
print(element)
The list is: [31, 42, 13, 34, 85, 0, 99, 1, 3] The elements in odd positions are: 42 34 0 1
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
range(1, len, 2) |
High | Fast | Direct index access |
[1::2] slicing |
Very High | Fast | Creating new list |
enumerate() |
Medium | Slower | When you need both index and value |
Conclusion
Use range(1, len(list), 2) for simple iteration or list slicing [1::2] for concise code. Both methods efficiently access elements at odd positions (indices 1, 3, 5, etc.).
Advertisements
