Remove empty array python

Python Programming: The Ultimate Guide to Remove Empty Array Elements Easily

Learn how to remove empty array elements in Python with join(), split(), list comprehension, filter(), and recursive functions. Improve your Python coding skills today!

  • Using join() and split() to remove empty strings from a list in Python
  • Using list comprehension to remove empty elements from a list in Python
  • Python tutorial — How to Remove Empty Lists from a List
  • Using filter() to remove empty elements from a list in Python
  • Using a recursive function to remove empty lists from a list in Python
  • Best practices for Python coding
  • Other simple code samples for removing empty array elements in Python
  • Conclusion
  • How do you remove blank elements from an array in Python?
  • How do you remove empty elements from an array?
  • How do you delete empty elements?
  • How do you remove all null values from a list in Python?

Python is a high-level, interpreted programming language that is known for its simplicity, readability, and ease of use. It is widely used for data analysis, machine learning, web development, and scientific computing. One common task in Python programming is to remove empty elements from an array or list. This tutorial will provide you with a comprehensive guide to removing empty elements from an array or list in Python.

Читайте также:  Define php в классе

Using join() and split() to remove empty strings from a list in Python

The join() method can be used to concatenate all elements in a list into a single string with a specified separator. The split() method can be used to split a string into a list based on a specified separator. By using join() and split() together, empty strings can be removed from a list by replacing them with a space and then splitting the resulting string.

Here is an example code that demonstrates the use of join() and split() to remove empty strings from a list in Python:

my_list = ['hello', '', 'world', '', ''] new_list = ' '.join(my_list).split() print(new_list) 

In the above example, we first join all the elements of the list using the join() method and replace the empty strings with a space. Then, we split the resulting string into a list using the split() method. This results in a new list that does not contain any empty strings.

Using list comprehension to remove empty elements from a list in Python

List comprehension is a concise way to create and modify lists in python . By using an if statement in list comprehension, empty elements can be removed from a list.

Here is an example code that demonstrates the use of list comprehension to remove empty elements from a list in Python:

my_list = ['hello', '', 'world', '', ''] new_list = [x for x in my_list if x] print(new_list) 

In the above example, we use list comprehension to iterate over each element in the list and check if it is not empty. If an element is not empty, it is added to the new list. This results in a new list that does not contain any empty strings.

Читайте также:  Галерея

Python tutorial — How to Remove Empty Lists from a List

Using filter() to remove empty elements from a list in Python

The filter() method can be used to filter out elements from a list based on a given function. By using lambda function with filter(), empty elements can be removed from a list.

Here is an example code that demonstrates the use of filter() to remove empty elements from a list in Python:

my_list = ['hello', '', 'world', '', ''] new_list = list(filter(lambda x: x != '', my_list)) print(new_list) 

In the above example, we use filter() to iterate over each element in the list and check if it is not empty. If an element is not empty, it is added to the new list. This results in a new list that does not contain any empty strings.

Using a recursive function to remove empty lists from a list in Python

A recursive function is a function that calls itself within its definition. A recursive function can be used to remove empty lists from a list.

Here is an example code that demonstrates the use of a recursive function to remove empty lists from a list in Python:

my_list = [1, [], 2, [3, []], [[]], 4, []] def remove_empty_lists(lst): return [x for x in lst if x != [] and x != remove_empty_lists([])] new_list = remove_empty_lists(my_list) print(new_list) 

In the above example, we define a recursive function named remove_empty_lists() that takes a list as input and returns a new list that does not contain any empty lists. The function first checks if an element is empty list or not. If an element is not an empty list, it is added to the new list. If an element is an empty list, the function calls itself with an empty list as input until there are no empty lists left in the list.

Best practices for Python coding

using descriptive variable names and commenting code can make code more readable and understandable. List comprehension can be used to make code more concise and efficient. Avoiding unnecessary loops can improve the performance of code.

Here is an example code that demonstrates the use of best practices for python coding :

# Example of using descriptive variable names and comments my_list = ['hello', '', 'world', '', ''] # Remove empty strings from my_list using join() and split() new_list = ' '.join(my_list).split() print(new_list)# Example of using list comprehension to make code more concise my_list = ['hello', '', 'world', '', ''] new_list = [x for x in my_list if x] print(new_list)# Example of avoiding unnecessary loops my_list = ['hello', '', 'world', '', ''] new_list = [] for x in my_list: if x != '': new_list.append(x) print(new_list) 

In the above example, we have used descriptive variable names and comments to make the code more readable and understandable. We have also used list comprehension to make the code more concise and efficient. Lastly, we have avoided an unnecessary loop by using an if statement to check if an element is not empty.

Other simple code samples for removing empty array elements in Python

In Python case in point, empty array python code example

import numpy my_array = numpy.zeros(shape=(row,column))

Conclusion

Removing empty elements from an array or list is a common task in Python programming. There are several ways to accomplish this task, including using join() and split(), list comprehension, filter(), and recursive functions. It is important to use best practices for python coding, such as using descriptive variable names and commenting code, to make code more readable and understandable.

Источник

Remove any empty list present in the list

This will work only if you are sure that your array is two-dimensional. If there are more dimensions or there are non-array elements in the outer array, you will fail.

10 Answers 10

Use a recursive function to remove the empty list from a list.
Using recursion you can remove an empty list to any depth:

def remove_nested_list(listt): for index, value in enumerate(reversed(listt)): if isinstance(value, list) and value != []: remove_nested_list(value) elif isinstance(value, list) and len(value) == 0: listt.remove(value) a = [[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]] print(f"before-->") remove_nested_list(a) print(f"after-->") 

Output:

before-->[[1, 2, 3, 0, []], [], [], [], [4, 5, [], 7]] after-->[[1, 2, 3, 0], [4, 5, 7]] 

Another interesting consideration is what to do with [[]] . It looks like your code would remove the inner empty list, leaving [] . I don’t know if that would be the desired outcome or not.

@Teepeemm Nice edge-case man. I guess we need two recursive functions one for checking if it’s empty nested list, second for removing them.

To remove empty lists from the arbitrarily nested list. We can use recursion here. Here’s a simple way to do it. We need to iterate through the list and check if an element is an empty list. If yes, then we don’t add it to the final list. If it’s not an empty list we repeat the above process.

def remove_empty(lst): return ( [remove_empty(i) for i in lst if i!=[]] if isinstance(lst, list) else lst ) 
i = [[1, 2, 3, []], [], [], [], [4, 5, [], 7]] print(remove_empty(i)) # [[1, 2, 3], [4, 5, 7]] # Example taken from iGian's answer ii = [[1, 2, 3, []], [], [], [], [4, 5, [], 7, [8, 9, [], [10, 11, []]]]] print(remove_empty(ii)) # [[1, 2, 3], [4, 5, 7, [8, 9, [10, 11]]]] 

To check if an object is iterable we use collection.abc.iterable

from collections.abc import Iterable all( isinstance(i, Iterable) for i in ([], tuple(), set(), dict(), range(10), (_ for _ in range(10))) ) # True 

Now, you can replace isinstance(lst, list) with isinstance(lst, Iterable) to filter out empty list i.e [] from every iterable.

Edit:

@Teepeemm pointed out a wonderful corner-case which all the answers missed.

To solve it we need two recursive functions one for checking if it’s an empty nested list and the second one for remove empty nested lists

def empty(lst): if lst == []: return True elif isinstance(lst, list): return all(empty(i) for i in lst) else: return False def remove_empty(lst): return ( [remove_empty(i) for i in lst if not empty(i)] if isinstance(lst, list) else lst ) i = [[1, 2, 3, [[]]]] remove_empty(i) # [[1, 2, 3]] remove_nested_list(i) # Muhammad Safwan's answer print(i) # [[1, 2, 3, []]] ii = [[1, 2, 3, [[], [[[[], []]]]]]] remove_empty(ii) # [[1, 2, 3]] remove_nested_list(ii) # Muhammad Safwan's answer print(ii) # [[1, 2, 3, [[[[]]]]]] 

I would use a couple of methods that doesn’t mutate the original list.

The first simply removes all the empty lists in a list, not the nested:

def remove_empty_lists(lst): return [ e for e in lst if not (isinstance(e, list) and len(e)==0) ] 

The second method just uses the former in a recursive way:

def deep_remove_empty_lists(lst): lst = remove_empty_lists(lst) return [ deep_remove_empty_lists(e) if isinstance(e, list) else e for e in lst ] 
i = [[1,2,3,[]],[],[],[],[4,5,[],7]] deep_remove_empty_lists(i) #=> [[1, 2, 3], [4, 5, 7]] 

Or in a deepest nesting case:

ii = [[1,2,3,[]],[],[],[],[4,5,[],7,[8, 9, [], [10, 11, []]]]] deep_remove_empty_lists(ii) #=> [[1, 2, 3], [4, 5, 7, [8, 9, [10, 11]]]] 

You can use list comprehension(actually nested comprehension) :

i = [[1, 2, 3, []], [], [], [], [4, 5, [], 7]] res = [[sub_item for sub_item in item if sub_item != []] for item in i if item != []] print(res) 

We check for empty lists two times, one for container lists in i with if item != [] and one for individual elements inside those containers with if sub_item != [] .

It’s more Pythonic to say if item than if item != [] . Although that’s assuming that item is always a list which may be empty, and never something else that may be Falsey like 0 or None.

If the nesting always two levels deep, i.e. as in your question, a clean way would be:

>>> not_empty_list = lambda value: value != [] ## Above is equivalent to: # not_empty_list = [].__ne__ # not_empty_list = functools.partial(operator.ne, [])) >>> result = [ list(filter(not_empty_list, inner_list)) for inner_list in i if not_empty_list(inner_list) ] >>> result [[1, 2, 3], [4, 5, 7]] 
>>> i [[1, 2, 3, []], [], [], [], [4, 5, [], 7], [[]]] >>> result = [ list(filter(not_empty_list, inner_list)) for inner_list in i if not_empty_list(inner_list) ] >>> list(filter(not_empty_list, result)) [[1, 2, 3], [4, 5, 7]] 

If you need to be able to handle lists nested arbitrarily deeply, and also want to remove e.g. [[]] or [[], [[], []]] or other lists containing nothing but (lists containing nothing but) empty lists, here’s a simple recursive solution:

def simplify(value): if isinstance(value, list): return [y for y in (simplify(x) for x in value) if y != []] else: return value print(simplify([[1,2,3,[]],[],[],[],[4,5,[],7],[[],[[]]],[[],[8]]])) 

The main difference between this solution and most (all?) of the other recursive ones posted so far is that it first recursively simplifies any sublists it encounters and then skips any sublists that are empty after simplification. This is what allows it to also skip sublists like [[]] .

(Note, however, that this function will still always return a list if given a list, even if that list may be empty. For example, simplify([[], [[]]]) will still return [] instead of, say, None . If you want to have some special handling for the case where the top-level list is empty after simplification, you’ll need to check for that separately. But at least after running the list through the function above, you can check for that case just using e.g. if simplified_list == []: .)

Источник

Оцените статью