Given a list, the task is to remove trailing None values from last of the list. Let’s discuss a few methods to solve the given task.
Examples:
Input: [1, 2, 3, 4, None, 76, None, None]
Output: [1, 2, 3, 4, None, 76]
Input: [1, 2, None, None, None, None, None, 5]
Output: [1, 2, None, None, None, None, None, 5]
Method #1: Using naive method
Python3
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ("initial dictionary", str (ini_list))
while not ini_list[ - 1 ]:
ini_list.pop()
print ("resultant list ", str (ini_list))
|
Output:
initial dictionary [1, 2, 3, 4, None, 76, None, None, None]
resultant list [1, 2, 3, 4, None, 76]
Method #2: Using itertools.dropwhile()
Python3
from itertools import dropwhile
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ("initial dictionary", str (ini_list))
res = list ( reversed ( tuple (dropwhile( lambda x: x is None ,
reversed (ini_list)))))
print ("resultant list ", str (res))
|
Output:
initial dictionary [1, 2, 3, 4, None, 76, None, None, None]
resultant list [1, 2, 3, 4, None, 76]
Method #3: Using itertools.takewhile()
Python3
from itertools import takewhile
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ("initial dictionary", str (ini_list))
res = ini_list[: - len ( list (takewhile( lambda x: x = = None ,
reversed (ini_list))))]
print ("resultant list ", str (res))
|
Output:
initial dictionary [1, 2, 3, 4, None, 76, None, None, None]
resultant list [1, 2, 3, 4, None, 76]
Method #4: Using enumerate and list comprehension
Python3
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ("initial dictionary", str (ini_list))
res = [x for n, x in enumerate (ini_list)
if any (y is not None for y in ini_list[n:])]
print ("resultant list ", str (res))
|
Output:
initial dictionary [1, 2, 3, 4, None, 76, None, None, None]
resultant list [1, 2, 3, 4, None, 76]
Method #5: Looping from end using list comprehension
Both the list comprehension and lambda function versions are concise and efficient, since they only need to iterate through the list once.
Here is an example of this approach:
Python3
def remove_trailing_none(lst):
index = next ((i for i in range ( len (lst) - 1 , - 1 , - 1 ) if lst[i] is not None ), - 1 )
return lst[:index + 1 ]
print (remove_trailing_none([ 1 , 2 , 3 , 4 , None , 76 , None , None ]))
print (remove_trailing_none([ 1 , 2 , None , None , None , None , None , 5 ]))
print (remove_trailing_none([ None , None , None ]))
|
Output
[1, 2, 3, 4, None, 76]
[1, 2, None, None, None, None, None, 5]
[]
Time complexity: O(n)
Auxiliary space: O(1)
Method #6: Using slicing
Python3
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ( "initial list" , str (ini_list))
ini_list = ini_list[:: - 1 ]
index = 0
for i in range ( len (ini_list)):
if (ini_list[i]):
index = i
break
res = ini_list[index::]
res = res[:: - 1 ]
print ( "resultant list" , str (res))
|
Output
initial list [1, 2, 3, 4, None, 76, None, None, None]
resultant list [1, 2, 3, 4, None, 76]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method#7: Using Recursive method.
The function takes a list as input and returns a new list with all trailing None elements removed. Here is how it works:
If the input list is empty, return the empty list.
If the last element of the list is None, remove it by calling the remove_trailing_none function recursively with the list up to the second to last element.
If the last element is not None, return the input list as it is.
Python3
def remove_trailing_none(lst):
if not lst:
return lst
elif lst[ - 1 ] is None :
return remove_trailing_none(lst[: - 1 ])
else :
return lst
ini_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ( "initial dictionary" , str (ini_list))
res = remove_trailing_none(ini_list)
print ( "resultant list" , str (res))
|
Time Complexity:
The time complexity of the remove_trailing_none() function is O(n), where n is the length of the input list. This is because in the worst case, the function will need to traverse the entire list once to remove all the trailing None elements.
Space Complexity:
The space complexity of the remove_trailing_none() function is also O(n), where n is the length of the input list. This is because in the worst case, the function will need to create a new list to store the result, which will be of the same size as the input list.
Method#8: Using a for loop and the reversed() function:
1.Start by iterating over the indices of the list in reverse order.
2.For each index i, check if the element at that index is not None.
3.If it is not None, return a slice of the original list up to and including that index.
4.If all elements of the list are None, return an empty list.
Python3
def remove_trailing_none(lst):
for i in reversed ( range ( len (lst))):
if lst[i] is not None :
return lst[:i + 1 ]
return []
my_list = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
print ( "initial dictionary" , str (my_list))
new_list = remove_trailing_none(my_list)
print (new_list)
|
Output
initial dictionary [1, 2, 3, 4, None, 76, None, None, None]
[1, 2, 3, 4, None, 76]
The time complexity :O(n), where n is the length of the input list. This is because in the worst case, we may have to iterate over the entire list to find the last non-None element.
The auxiliary space : O(1), because we are not creating any new data structures or using any extra memory. The only memory used is for the input list and any temporary variables created during the function’s execution.
Method#9:Using while loop and slicing
Here’s a step-by-step breakdown of the code:
- lst = [1, 2, 3, 4, None, 76, None, None, None]: Initialize a list with some values and None elements.
- while lst and lst[-1] is None: lst = lst[:-1]: Use a while loop to remove trailing None elements from the list.
- a. while lst: Keep looping as long as the list is not empty.
- b. lst[-1] is None: Check if the last element of the list is None.
- c. lst = lst[:-1]: If the last element of the list is None, remove it from the list by slicing it up to but not including the last element.
- print(lst): Print the final list with trailing None elements removed.
Python3
lst = [ 1 , 2 , 3 , 4 , None , 76 , None , None , None ]
while lst and lst[ - 1 ] is None :
lst = lst[: - 1 ]
print (lst)
|
Output
[1, 2, 3, 4, None, 76]
The time complexity of this code is O(n), where n is the length of the input list. This is because the while loop iterates over the list at most n times, and each iteration involves checking the value of the last element and slicing the list.
The space complexity is also O(n), because the original list is modified in place. However, the space complexity can be reduced by creating a new list with the non-None elements, as in the previous examples
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...