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
Python program to replace first 'K' elements by 'N'
When it is required to replace first 'K' elements by 'N', a simple iteration is used. This operation modifies the original list by substituting the first K elements with a specified value N.
Basic Approach Using Loop
The simplest method uses a for loop with range() to iterate through the first K positions ?
my_list = [13, 34, 26, 58, 14, 32, 16, 89]
print("The list is :")
print(my_list)
K = 2
print("The value of K is :")
print(K)
N = 99
print("The value of N is :")
print(N)
for index in range(K):
my_list[index] = N
print("The result is :")
print(my_list)
The list is : [13, 34, 26, 58, 14, 32, 16, 89] The value of K is : 2 The value of N is : 99 The result is : [99, 99, 26, 58, 14, 32, 16, 89]
Using List Slicing
An alternative approach uses list slicing to replace multiple elements at once ?
numbers = [13, 34, 26, 58, 14, 32, 16, 89]
K = 3
N = 50
print("Original list:", numbers)
numbers[:K] = [N] * K
print("After replacing first", K, "elements with", N, ":", numbers)
Original list: [13, 34, 26, 58, 14, 32, 16, 89] After replacing first 3 elements with 50 : [50, 50, 50, 58, 14, 32, 16, 89]
How It Works
A list of integers is defined and displayed on the console.
The value for 'K' (number of elements to replace) and 'N' (replacement value) are defined.
The
range(K)generates indices from 0 to K-1.Each element at these positions is assigned the value N.
The slicing method
[:K] = [N] * Kreplaces the first K elements in one operation.
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Loop with range() | High | Good | Learning purposes |
| List slicing | Medium | Better | Concise code |
Conclusion
Both methods effectively replace the first K elements with value N. The loop approach is more readable for beginners, while slicing offers a more concise solution for experienced programmers.
