Python program to replace first ‘K’ elements by ‘N’
Last Updated :
21 Apr, 2023
Given a List, replace first K elements by N.
Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 4, N = 3
Output : [3, 3, 3, 3, 4, 2, 6, 9]
Explanation : First 4 elements are replaced by 3.
Input : test_list = [3, 4, 6, 8, 4, 2, 6, 9], K = 2, N = 10
Output : [10, 10, 6, 8, 4, 2, 6, 9]
Explanation : First 2 elements are replaced by 10.
Method 1: Using a loop
This naive method iterates through the list ‘k‘ number of times and assigns ‘N‘ to each element encountered till the loop ends.
Python3
test_list = [ 3 , 4 , 6 , 8 , 4 , 2 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
K = 5
N = 6
for idx in range (K):
test_list[idx] = N
print ( "Elements after replacement : " + str (test_list))
|
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Method 2: Using list slicing
In this, we slice off, just a few elements from the list and assign ‘N‘ to the sliced list.
Python3
test_list = [ 3 , 4 , 6 , 8 , 4 , 2 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
K = 5
N = 6
test_list[: K] = [N] * K
print ( "Elements after replacement : " + str (test_list))
|
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Method 3: Using list(),map(),join() and replace()
Initially convert each element of list to string and then join the list using empty string.Replace first K characters with N in that joined list(which is a string) ,later convert each element of a string to integer and make it a list.
Python3
test_list = [ 3 , 4 , 6 , 8 , 4 , 2 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
K = 5
N = 6
a = list ( map ( str ,test_list))
b = "".join(a)
b = b.replace(b[:K], str (N) * K)
b = list ( map ( int ,b))
print ( "Elements after replacement : " + str (b))
|
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Method 4:Using list comprehension
Algorithm
- Initialize the list test_list with some values.
- Initialize the value of K and N.
- Iterate over the first K elements of the list using a for loop and list comprehension.
- If the index is less than K, replace the value at that index with N, else keep the original value.
- Print the updated list test_list.
Python3
test_list = [ 3 , 4 , 6 , 8 , 4 , 2 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
K = 5
N = 6
test_list = [N if idx < K else val for idx, val in enumerate (test_list)]
print ( "Elements after replacement : " + str (test_list))
|
Output
The original list is : [3, 4, 6, 8, 4, 2, 6, 9]
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Time complexity:
Initializing the list takes O(n) time, where n is the length of the list.
Initializing K and N takes constant time, i.e., O(1).
The for loop that iterates over the first K elements takes O(K) time.
The list comprehension takes O(K) time.
Printing the updated list takes O(n) time.
Therefore, the overall time complexity is O(n + K).
Space complexity:
The space required to store the input list test_list is O(n).
The space required to store the variables K and N is constant, i.e., O(1).
The space required by the list comprehension is also O(n).
Therefore, the overall space complexity is O(n).
Method 5 : use the extend() method of lists
Steps:
Initialize the list test_list.
Initialize the values of K and N.
Use list slicing to select the sublist of test_list up to index K.
Replace the selected sublist with a list of K copies of N using the = assignment operator and the * operator.
Print the resulting list.
Python3
test_list = [ 3 , 4 , 6 , 8 , 4 , 2 , 6 , 9 ]
K = 5
N = 6
test_list[:K] = [N] * K
print ( "Elements after replacement : " + str (test_list))
|
Output
Elements after replacement : [6, 6, 6, 6, 6, 2, 6, 9]
Time complexity: O(K)
Auxiliary space: O(K)
Similar Reads
Python Program to Replace Text in a File
In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text. Method 1: Removing all text and write new t
3 min read
Python program to remove last element from set
Given a set, the task is to write a Python program to delete the last element from the set. Example: Input: {1,2,3,4}Remove 4Output: {1,2,3} Input: {"Geeks","For"}Remove GeeksOutput: {"For"}Explanation: The idea is to remove the last element from the set 4 in the first case and "Geeks" in the second
2 min read
Python program to remove last element from Tuple
Given a tuple, the task is to write a Python program to delete the last element in the tuple in Python. Example: Input: ("geeks", "for", "geeks") Output:("geeks", "for") Explanation: Here we are deleting the last element of the tuple and finally modifying the original one. Note: Tuples are immutable
3 min read
Python Program to Swap Two Elements in a List
In this article, we will explore various methods to swap two elements in a list in Python. The simplest way to do is by using multiple assignment. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Swapping elements at index 0 and 4 # using multiple assignment a[0], a[4] = a[4], a[0] print(a) [/GF
2 min read
Python - Replace Elements greater than K
Given element list, replace all elements greater than K with given replace character. Input : test_list = [3, 4, 7, 5, 6, 7], K = 5, repl_chr = None Output : [3, 4, None, 5, None, None] Explanation : Characters are replaced by None, greater than 5. Input : test_list = [3, 4, 7, 5, 6, 7], K = 4, repl
4 min read
Python | Replace list elements with its ordinal number
Given a list of lists, write a Python program to replace the values in the inner lists with their ordinal values. Examples: Input : [[1, 2, 3], [ 4, 5, 6], [ 7, 8, 9, 10]]Output : [[0, 0, 0], [1, 1, 1], [2, 2, 2, 2]]Input : [['a'], [ 'd', 'e', 'b', 't'], [ 'x', 'l']]Output : [[0], [1, 1, 1, 1], [2,
5 min read
Python program to Remove the last element from list
Given a list of numbers or strings, the task is to write a Python program to remove the last element from a list. Example: Input : [12,53,11,76,22,21] Output : [12,53,11,76,22] Input : ["abc","gfg","text","python"] Output : ["abc","gfg","text"] The application of this type of problem in day-day prog
3 min read
Python Program to replace list elements within a range with a given number
Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is u
3 min read
Python Program to replace elements of a list based on the comparison with a number
Given a list, the task here is to write a Python program to replace its elements after comparing them with another number here described using K. For the example depicted in this article, any number greater than K will be replaced with the value given in high and any number less than or equal to K w
4 min read
Python - Replace sublist from Initial element
Given a list and replacement sublist, perform the replacement of list sublist on basis of initial element of replacement sublist. Input : test_list = [3, 7, 5, 3], repl_list = [7, 8] Output : [3, 7, 8, 3] Explanation : Replacement starts at 7 hence 7 and 8 are replaced. Input : test_list = [3, 7, 5,
7 min read