Program to replace kth element in the list with n using Python

Introduction

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.

Program to replace kth element in the list with n

Program

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)

Output

Program to replace kth element in the list with n Output

Explanation

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.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.