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
Multiply K to every Nth element using Python
In this problem, we need to multiply K to every Nth element in a given list using Python. We'll explore two approaches: using basic Python and using NumPy for efficient array operations.
Understanding the Problem
We have a list and need to multiply a constant K with elements at positions that are multiples of N. For example, if N=2, we multiply every 2nd element (positions 2, 4, 6, etc.) by K.
Method 1: Using Basic Python
We iterate through the list with a counter and multiply elements at positions divisible by N ?
def multiply_nth_element(data, K, N):
"""Multiply K to every Nth element in the list"""
count = 1
for i in range(len(data)):
if count % N == 0:
data[i] *= K
count += 1
return data
# Example usage
numbers = [10, 20, 30, 40, 50, 60]
K = 3
N = 2
result = multiply_nth_element(numbers.copy(), K, N)
print(f"Original: {[10, 20, 30, 40, 50, 60]}")
print(f"Result: {result}")
Original: [10, 20, 30, 40, 50, 60] Result: [10, 60, 30, 120, 50, 180]
Method 2: Using NumPy
NumPy provides efficient array operations using boolean indexing ?
import numpy as np
def multiply_nth_element_numpy(data, K, N):
"""Multiply K to every Nth element using NumPy"""
arr = np.array(data)
indices = np.arange(len(arr))
# Create boolean mask for positions divisible by N (1-indexed)
mask = (indices + 1) % N == 0
arr[mask] *= K
return arr.tolist()
# Example usage
numbers = [10, 20, 30, 40, 50, 60]
K = 3
N = 2
result = multiply_nth_element_numpy(numbers, K, N)
print(f"Original: {numbers}")
print(f"Result: {result}")
Original: [10, 20, 30, 40, 50, 60] Result: [10, 60, 30, 120, 50, 180]
Method 3: Using List Comprehension
A more Pythonic approach using list comprehension with enumerate ?
def multiply_nth_element_comprehension(data, K, N):
"""Multiply K to every Nth element using list comprehension"""
return [item * K if (i + 1) % N == 0 else item
for i, item in enumerate(data)]
# Example usage
numbers = [10, 20, 30, 40, 50, 60]
K = 3
N = 2
result = multiply_nth_element_comprehension(numbers, K, N)
print(f"Original: {numbers}")
print(f"Result: {result}")
Original: [10, 20, 30, 40, 50, 60] Result: [10, 60, 30, 120, 50, 180]
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Basic Python | O(n) | O(1) | In-place modification |
| NumPy | O(n) | O(n) | Large arrays |
| List Comprehension | O(n) | O(n) | Functional style |
Conclusion
All three methods efficiently multiply K to every Nth element with O(n) time complexity. Use the basic Python approach for in-place modification, NumPy for large datasets, or list comprehension for clean, readable code.
