Python – Replace Non-None with K

Sometimes, while working with Python lists we can have a problem in which we need to perform the replacment of all the elements that are non-None. This kind of problem can have application 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 replacement inside comprehension as one liner using conditions.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.