Python – Next N elements from K value


When it is required to get next N elements from K value, a simple iteration is used.

Below is a demonstration of the same −

Example

my_list = [31, 24, 46, 18, 34, 52, 26, 29]
print("The list is :")
print(my_list)
K = 2
print("The value of K is :")
print(K)
N = 3
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 :
[31, 24, 46, 18, 34, 52, 26, 29]
The value of K is :
2
The value of N is :
3
The result is :
[3, 3, 46, 18, 34, 52, 26, 29]

Explanation

  • A list is defined and displayed on the console.

  • The values for K and N are defined and displayed on the console.

  • The list is iterated over in the range of K, and the value of N is assigned the element at specific indices.

  • This is the output that is displayed on the console.

Updated on: 08-Sep-2021

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements