
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to replace first ‘K’ elements by ‘N’
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’.
- Related Articles
- Python Program to Replace Elements in a Tuple
- Python Program to Reverse only First N Elements of a Linked List
- Python – Next N elements from K value
- Python program to find Non-K distant elements
- Python – Remove Elements in K distance with N
- Program to find k where k elements have value at least k in Python
- Python Program to Get K initial powers of N
- 8086 program to determine modulus of first array elements corresponding to another array elements\n
- How to group Python tuple elements by their first element?
- Program to generate first n lexicographic numbers in python
- Python program to randomly create N Lists of K size
- Program to find minimum amplitude after deleting K elements in Python
- Trim tuples by N elements in Python
- Java Program to Replace Elements in a List
- Golang program to replace elements in a slice

Advertisements