Skip to content
Related Articles

Related Articles

Improve Article

Python program to replace first ‘K’ elements by ‘N’

  • Last Updated : 01 Oct, 2020

Given a List, replace first K elements by N.

Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3 
Output : [3, 3, 3, 3, 4, 2, 6, 9] 
Explanation : First 4 elements are replaced by 3.

Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10 
Output : [10, 10, 6, 8, 4, 2, 6, 9] 
Explanation : First 2 elements are replaced by 10. 
 

Method 1: Using a loop

This naive method iterates through the list ‘k‘ number of times and assigns ‘N‘ to each element encountered till the loop ends.



Python3




# initializing list
test_list = [3, 4, 6, 8, 4, 2, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# initializing N
N = 6
  
# assigning value 'N' till K elements
for idx in range(K):
  
    test_list[idx] = N
  
# printing result
print("Elements after replacement : " + str(test_list))
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]

 
Method 2: Using list slicing

 In this, we slice off, just a few elements from the list and assign ‘N‘ to the sliced list.

Python3




# initializing list
test_list = [3, 4, 6, 8, 4, 2, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# initializing N
N = 6
  
# assigning the N value till K elements
test_list[: K] = [N] * K
  
# printing result
print("Elements after replacement : " + str(test_list))
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up