Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Remove trailing empty elements from given list

Python | Remove trailing empty elements from given list

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




# Python code to demonstrate
# to remove trailing None
# elements from lists
 
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print ("initial dictionary", str(ini_list))
 
# code toremove trailing None values
# from lists
while not ini_list[-1]:
    ini_list.pop()
     
# printing result
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




# Python code to demonstrate
# to remove trailing None
# elements from lists
 
from itertools import dropwhile
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print ("initial dictionary", str(ini_list))
 
# code toremove trailing None values
# from lists
res = list(reversed(tuple(dropwhile(lambda x: x is None,
                                    reversed(ini_list)))))
     
# printing result
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




# Python code to demonstrate
# to remove trailing None
# elements from lists
 
from itertools import takewhile
 
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print ("initial dictionary", str(ini_list))
 
# code toremove trailing None values
# from lists
res = ini_list[:-len(list(takewhile(lambda x: x == None,
                                  reversed(ini_list))))]
# printing result
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




# Python code to demonstrate
# to remove trailing None
# elements from lists
 
 
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print ("initial dictionary", str(ini_list))
 
# code toremove trailing None values
# from lists
res = [x for n, x in enumerate(ini_list)
       if any(y is not None for y in ini_list[n:])]
 
# printing result
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):
    # Find the index of the last non-None value
    index = next((i for i in range(len(lst)-1, -1, -1) if lst[i] is not None), -1)
    # Return the original list up to this index
    return lst[:index+1]
 
# Test the function
print(remove_trailing_none([1, 2, 3, 4, None, 76, None, None]))  # Output: [1, 2, 3, 4, None, 76]
print(remove_trailing_none([1, 2, None, None, None, None, None, 5]))  # Output: [1, 2, None, None, None, None, None, 5]
print(remove_trailing_none([None, None, None]))  # Output: []
 
#This code is contributed by Edula Vinay Kumar Reddy


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




# Python code to demonstrate
# to remove trailing None
# elements from lists
 
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print("initial list", str(ini_list))
 
# reverse 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]
# printing result
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




# Python code to demonstrate
# to remove trailing None
# elements from lists
def remove_trailing_none(lst):
    if not lst:
        return lst
    elif lst[-1] is None:
        return remove_trailing_none(lst[:-1])
    else:
        return lst
 
 
# initialising lists
ini_list = [1, 2, 3, 4, None, 76, None, None, None]
 
# printing initial dictionary
print ("initial dictionary", str(ini_list))
 
# code toremove trailing None values
# from lists
res =remove_trailing_none(ini_list)
 
# printing result
print ("resultant list", str(res))
#this code contributed by tvsk


 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):
    # Iterate over the indices of the list in reverse order
    for i in reversed(range(len(lst))):
        # If we find an element that is not None,
        # then return a slice of the original list up to this index (inclusive)
        if lst[i] is not None:
            return lst[:i+1]
    # If we haven't found any non-None elements, then return an empty list
    return []
     
# Example usage
my_list = [1, 2, 3, 4, None, 76, None, None, None]
# printing initial dictionary
print ("initial dictionary", str(my_list))
  
new_list = remove_trailing_none(my_list)
print(new_list)
#This code is contributed by Jyothi pinjala.


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:

  1. lst = [1, 2, 3, 4, None, 76, None, None, None]: Initialize a list with some values and None elements.
  2. while lst and lst[-1] is None: lst = lst[:-1]: Use a while loop to remove trailing None elements from the list.
  3. a. while lst: Keep looping as long as the list is not empty.
  4. b. lst[-1] is None: Check if the last element of the list is None.
  5. 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.
  6. 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)
 
#This code is contributed by Vinay Pinjala.


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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments