Python – Replace Non-None with K
Last Updated :
15 May, 2023
Sometimes, while working with Python lists we can have a problem in which we need to perform the replacement of all the elements that are non-None. This kind of problem can have applications in many domains such as web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [2, None, None, 5, ''], K = 9
Output : [9, None, None, 9, '']
Input : test_list = ['', None], K = 10
Output : ['', None]
Method #1: Using list comprehension
This is one of the ways in which this task can be performed. In this, we perform the task of traversing and replacing inside comprehension as one-liner using conditions.
Python3
test_list = [ 59 , 236 , None , 3 , '']
print ( "The original list : " + str (test_list))
K = 'Gfg'
res = [K if ele else ele for ele in test_list]
print ( "List after replacement : " + str (res))
|
Output :
The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary Space: O(n), because we are creating a new list of the same length as the input list to store the result
Method #2: Using map() + lambda()
The combination of the above functions can be used to solve this problem. In this, we perform the task of extending lambda logic to entire list using map() and perform replacement.
Python3
test_list = [ 59 , 236 , None , 3 , '']
print ( "The original list : " + str (test_list))
K = 'Gfg'
res = list ( map ( lambda ele: K if ele else ele, test_list))
print ( "List after replacement : " + str (res))
|
Output :
The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']
Time complexity: O(n), where n is the length of the input list.
The map() function operates on each element of the list in a single iteration, and the time complexity of the lambda function is constant. Therefore, the overall time complexity of the program is O(n).
Auxiliary Space: O(n), where n is the length of the input list.
A new list is created to store the modified elements, and its size is equal to the length of the input list. Therefore, the auxiliary space required by the program is O(n).
Method#3: using Loop
Approach:
- Initialize the original list, test_list.
- Print the original list.
- Initialize the value to be replaced with K.
- Iterate through the list using a for loop and range function.
- Check if the current element is None or an empty string using an if statement.
- If the current element is None or an empty string, replace it with K.
- Print the list after replacement.
Python3
test_list = [ 59 , 236 , None , 3 , '']
print ( "The original list : " + str (test_list))
K = 'Gfg'
for i in range ( len (test_list)):
if test_list[i] is None or test_list[i] = = '':
test_list[i] = K
elif not isinstance (test_list[i], str ):
test_list[i] = str (test_list[i])
print ( "List after replacement : " + str (test_list))
|
Output
The original list : [59, 236, None, 3, '']
List after replacement : [59, 236, 'Gfg', 3, 'Gfg']
Time Complexity: O(n), The program uses a single loop to iterate over all the elements in the original list, which takes O(n) time, where n is the length of the list.
Auxiliary Space: O(1), The program uses a fixed amount of extra memory to store the value of K and the loop index variable i. No additional data structure is used, and the original list is updated in place. Therefore, the space complexity is O(1).
Method 4: Using map() + lambda
Approach:
- initializing list
- printing original list
- initializing K
- Replace Non-None with K Using filter() + lambda()
- printing result
Below is the implementation of the above approach:
Python3
test_list = [ 59 , 236 , None , 3 , '']
print ( "The original list : " + str (test_list))
K = 'Gfg'
res = list ( map ( lambda ele: K if ele is None else ele, test_list))
print ( "List after replacement : " + str (res))
|
Output
The original list : [59, 236, None, 3, '']
List after replacement : [59, 236, 'Gfg', 3, '']
Time complexity: O(n) since we iterate over the list once. In terms of space complexity, it requires additional space to store the filtered values,
Auxiliary space: O(k) where k is the number of None values in the original list.
Method #5: Using numpy
It converts the list to a NumPy array, creates a boolean mask for non-None values, replaces them with K, and converts the NumPy array back to a list.
Python3
import numpy as np
test_list = [ 59 , 236 , None , 3 , '']
print ( "The original list : " + str (test_list))
K = 'Gfg'
arr = np.array(test_list)
mask = arr ! = None
arr[mask] = K
res = arr.tolist()
print ( "List after replacement : " + str (res))
|
Output
The original list : [59, 236, None, 3, '']
List after replacement : [59, 236, 'Gfg', 3, 'Gfg']
Time complexity: O(n), as we traverse the list once to create the NumPy array
Auxiliary space: O(n), n is the length of the input list
Similar Reads
Python - Replace None with Empty Dictionary
Given a dictionary, replace None values in every nesting with an empty dictionary. Input : test_dict = {"Gfg" : {1 : None, 7 : None}, "is" : None, "Best" : [1, { 5 : None }, 9, 3]} Output : {'Gfg': {1: {}, 7: {}}, 'is': {}, 'Best': [1, {5: {}}, 9, 3]} Explanation : All None values are replaced by em
4 min read
Replace multiple words with K - Python
We are given a string s and the task is to replace all occurrences of specified target words with a single replacement word K.For example, given text = "apple orange banana" and words_to_replace = ["apple", "banana"], the output will be "K orange K". Using List ComprehensionThis is the most efficien
4 min read
Python | Kth Non-None String from Rear
Sometimes while dealing with data science, we need to handle a large amount of data and hence we may require shorthands to perform certain tasks. We handle the Null values at preprocessing stage and hence sometimes require to check for the Kth valid element from rear. Letâs discuss certain ways in w
5 min read
Python - Replace K with Multiple values
Sometimes, while working with Python Strings, we can have a problem in which we need to perform replace of single character/work with particular list of values, based on occurrence. This kind of problem can have application in school and day-day programming. Let's discuss certain ways in which this
5 min read
Python | Check for None Tuple
Sometimes, while working with Python records, we can have a problem in which we need to filter out all the tuples which contain just None values. This can have a possible application in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using all() + gen
6 min read
Python - Remove Keys with K value
We are given a dictionary we need to remove the keys with K value. For example, we are having a dictionary d = {'a': 1, 'b': 2, 'c': 1, 'd': 3} we need to remove the keys which is having K value so that the output should be {'b': 2, 'd': 3} . We can use dictionary comprehension and many other method
4 min read
Python - Replace words from Dictionary
Replacing words in a string using a dictionary allows us to efficiently map specific words to new values. Using str.replace() in a LoopUsing str.replace() in a loop, you can systematically replace specific substrings within a string with new values. This approach is useful for repetitive replacement
3 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 vowels by next vowel
Given a String replace each vowel with next vowel in series. Input : test_str = 'geekforgeeks' Output : giikfurgiiks Explanation : After e, next vowel is i, all e replaced by i. Input : test_str = 'geekforgeeks is best' Output : giikfurgiiks os bist Explanation : After e, next vowel is i, all e repl
5 min read
Case insensitive string replacement in Python
We are given a string and our task is to replace a specific word in it, ignoring the case of the letters. This means if we want to replace the word "best" with "good", then all variations like "BeSt", "BEST", or "Best" should also be replaced. For example, if the input is "gfg is BeSt", then the out
3 min read