Table of Contents
In this section of python programming, the task is to replace the n number of element from the start with number k. Example, we want starting 3 elements of the list to be 2 and the rest of the elements will be the same.
input_list = [2, 3, 4, 5, 6] input_list1 = [2, 3, 4, 5, 6] n = int(input("Enter the number of elements you want to replace: ")) k = int(input("Enter the number you want to replace with: ")) # Using slicing input_list[:n] = [k]*n print("Output using slicing:",input_list) # Using for loop for i in range(n): input_list1[i] = k print("Output using loop:",input_list1)
In the above python code to achieve our task, we have used slicing property of list and the second method we used is loop. Using slicing, we have assigned the k value till n elements or we can say we have sliced till n elements and assigned the value k to it.
The for loop will iterate till n elements of the list and assign the value k at each index. When all values are traversed in the given range the output list is printed on the screen.