Skip to content
Related Articles

Related Articles

Python – Replace Non-None with K

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 17 Feb, 2022

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




# Python3 code to demonstrate working of 
# Replace Non-None with K
# Using list comprehension
  
# initializing list
test_list = [59, 236, None, 3, '']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing K 
K = 'Gfg'
  
# Replace Non-None with K
# Using list comprehension
res = [K if ele else ele for ele in test_list]
          
# printing result 
print("List after replacement : " + str(res))

Output :

The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']

 

Method #2 : Using map() + lambda()
The combination of 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




# Python3 code to demonstrate working of 
# Replace Non-None with K
# Using map() + lambda()
  
# initializing list
test_list = [59, 236, None, 3, '']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initializing K 
K = 'Gfg'
  
# Replace Non-None with K
# Using map() + lambda()
res = list(map(lambda ele: K if ele else ele, test_list))
          
# printing result 
print("List after replacement : " + str(res))

Output :

The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!