Python | K Divided Indices List

Python | K Divided Indices List

In this tutorial, we will learn how to find the indices in a list where the elements are divisible by k.

Problem Statement:

Given a list of integers, find all indices i such that the element at index i is divisible by k.

Approach:

  1. Iterate through the list.
  2. For each element, check if it is divisible by k.
  3. If it is, store its index.

Python Code:

def k_divided_indices(nums, k): # Using list comprehension to find indices return [idx for idx, num in enumerate(nums) if num % k == 0] # Example usage: nums = [2, 4, 5, 6, 8, 10, 12] k = 2 print(k_divided_indices(nums, k)) # Output: [0, 1, 3, 4, 5, 6] 

Explanation:

  1. We use the enumerate function to get both the index and value while iterating through the list.
  2. For each number, we check if it is divisible by k using the modulo operator %.
  3. If it's divisible, the index is added to the resulting list.

The method provides a simple and efficient way to find the indices of numbers in a list that are divisible by k.


More Tags

crystal-reports c#-2.0 managed-bean chrome-remote-debugging uifont visual-studio-2008 android-activity vision system.net compiler-errors

More Programming Guides

Other Guides

More Programming Examples