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

PythonServer Side ProgrammingProgramming

When it is required to replace first ‘K’ elements by ‘N’, a simple iteration is used.

## Example

Below is a demonstration of the same −

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)

## Output

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]

## Explanation

• A list of integers is defined and is displayed on the console.

• The value for ‘K’ and ‘N’ are defined and displayed on the console.

• The range within ‘K’ is iterated over, and every element in the index is assigned the value of N.

• This is done up to the values within index ‘K’.

Published on 08-Sep-2021 07:05:38