Program to find only even indexed elements from list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of elements called nums. We have to filter out all odd indexed elements, so only return even indexed elements from that list.

So, if the input is like nums = [5,7,6,4,6,9,3,6,2], then the output will be [7, 4, 9, 6]

To solve this, we will follow these steps −

  • use python list slicing strategy to solve this problem
  • start from index 1, end at the end of list and increase each step by 2, so the slicing
  • syntax is [1::2]

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   return nums[1::2]
nums = [5,7,6,4,6,9,3,6,2]
print(solve(nums))

Input

[5,7,6,4,6,9,3,6,2]

Output

[7, 4, 9, 6]
raja
Published on 12-Oct-2021 07:07:35

Advertisements