Table of Contents

Python code to return the elements on odd positions in a list.

 

Python code implementation without user defined functions & classes

Code: 
# Python code to return the elements on odd positions in a list.

a = [41, 19, 74, 107, 12309, -82, 64, 39, 501, 124, 70, 1111]

length_of_a = len(a)

for i in range(1, length_of_a, 2):
    print(a[i], end=" ")

 

Output: 
19 107 -82 39 124 1111
Python Code Editor Online - Click to Expand

 

Python code implementation using function

In this code we will take a list containing integer numbers. We will pass the list to a function that will return the list of elements on odd positions.

Code: 
# Python code to return the elements on odd positions in a list.
# Using Function

def return_odd_position_element(list_a):
    c = []
    for i in range(1, len(list_a), 2):
        c.append(a[i])
    return c

a = [41, 19, 74, 107, 12309, -82, 64, 39, 501, 124, 70, 1111]

odd_element_list = return_odd_position_element(a)
print(odd_element_list)

 

Output: 
[19, 107, -82, 39, 124, 1111]
Python Code Editor Online - Click to Expand

Python code implementation using Classes

In this code we will take a list containing integer numbers. We will implement a class that contain function to find elements on odd positions in a list. We will create an object and will call the function using object.function(), the will return the list of elements on odd positions.

Code: 
# Python code to return the elements on odd positions in a list.
# Using Classes

class Odd_position_element(object):
    def __init__(self, a):
        self.list_a = a


    def return_odd_position_element(self):
        c = []
        for i in range(1, len(self.list_a), 2):
            c.append(self.list_a[i])
        return c

a = [41, 19, 74, 107, 12309, -82, 64, 39, 501, 124, 70, 1111]

#Create an Object:
print_odd_list = Odd_position_element(a)

print(print_odd_list.return_odd_position_element())

 

Output: 
[19, 107, -82, 39, 124, 1111]
Python Code Editor Online - Click to Expand

 

Enjoy Python Code By Pythonbaba 🙂