# Python – Replace Non-None with K

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', '']```

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

 `# 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', '']```

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:

1. Initialize the original list, test_list.
2. Print the original list.
3. Initialize the value to be replaced with K.
4. Iterate through the list using a for loop and range function.
5. Check if the current element is None or an empty string using an if statement.
6. If the current element is None or an empty string, replace it with K.
7. Print the list after replacement.

## Python3

 `# 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` `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])`   `# printing result` `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:

1. initializing list
2. printing original list
3. initializing K
4. Replace Non-None with K Using filter() + lambda()
5. printing result

Below is the implementation of the above approach:

## Python3

 `# Python3 code to demonstrate working of ` `# Replace Non-None with K` `# Using filter() + 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 filter() + lambda()` `res ``=` `list``(``map``(``lambda` `ele: K ``if` `ele ``is` `None` `else` `ele, test_list))`   `# printing result ` `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

 `# Python code to demonstrate` `# replacing Non-None values in a list with K` `# using numpy`   `import` `numpy as np`   `# 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 numpy`   `# converting list to numpy array` `arr ``=` `np.array(test_list)`   `# creating a boolean mask of non-None values` `mask ``=` `arr !``=` `None`   `# replacing non-None values with K` `arr[mask] ``=` `K`   `# converting numpy array back to list` `res ``=` `arr.tolist()`   `# printing result` `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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next