Python remove empty lists

Python – Remove empty List from List Example

In this blog, I will show you how to remove empty list from list using python. We will talk about remove empty list from list in python.

This article will give you example for remove empty list in list using python. first example in using filter() to remove empty list and another example in you can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x != []] to filter the list.

Here i will give you two example for python remove empty list from list example. So let’s see the bellow example:

Example 1 : Using filter()

#Python Remove empty List from List using filter()

# Initializing list

myList = [1, [], 2, 3, [], 4, 5, [], [], 9]

# printing original list

print(«The original list is : » + str(myList))

# Remove empty List from List

result = list(filter(None, myList))

# printing result

print («List after empty list removal : » + str(result))

The original list is : [1, [], 2, 3, [], 4, 5, [], [], 9]

List after empty list removal : [1, 2, 3, 4, 5, 9]

# Python Remove empty List from List

# using list comprehension

# Initializing list

myList = [1, [], 2, 3, [], 4, 5, [], [], 9]

# printing original list

print(«The original list is : » + str(myList))

# Remove empty List from List

result = [ele for ele in myList if ele != []]

print («List after empty list removal : » + str(result))

The original list is : [1, [], 2, 3, [], 4, 5, [], [], 9]

List after empty list removal : [1, 2, 3, 4, 5, 9]

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

You might also like.

Источник

How to Remove Empty Lists from a List of Lists in Python?

remove all empty lists from list of lists

Be on the Right Side of Change

In the following, you’ll learn about the two methods using list comprehension and the filter() function to remove all empty lists from a list of lists.

But before that, feel free to play with the code yourself:

Method 1: List Comprehension

How can you remove all empty lists from a list of lists? Say, you’ve got a list of lists

and you want all empty lists removed to obtain the list of lists

Solution: Use list comprehension [x for x in list if x] to filter the list and remove all lists that are empty.

lst = [[1, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []] print([x for x in lst if x]) # [[1, 2, 3], [1, 2], [1, 2, 3, 4]]

The condition if x evaluates to False only if the list x is empty. In all other cases, it evaluates to True and the element is included in the new list.

You can visualize the execution flow here by clicking the “Next” button:

Method 2: filter()

An alternative is to use the filter() function to remove all empty lists from a list of lists:

lst = [[1, 2, 3], [1, 2], [], [], [], [1, 2, 3, 4], [], []] print(list(filter(lambda x: x, lst)))

The filter() function takes two arguments:

  • the filter decision function to check for each element whether it should be included in the filtered iterable (it returns a Boolean value), and
  • the iterable to be filtered.

As filter decision function, you use the identity function that just passes the list through. Why does this work? Because only an empty list will be evaluated to False . All other lists will be evaluated to True (and, thus, pass the filtering test).

Related articles:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Be on the Right Side of Change 🚀

  • The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
  • Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
  • Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.

Learning Resources 🧑‍💻

⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!

Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.

New Finxter Tutorials:

Finxter Categories:

Источник

Python: Remove empty lists from a given list of lists

Write a Python program to remove empty lists from a given list of lists.

Sample Solution:

Python Code:

list1 = [[], [], [], 'Red', 'Green', [1,2], 'Blue', [], []] print("Original list:") print(list1) print("\nAfter deleting the empty lists from the said lists of lists") list2 = [x for x in list1 if x] print(list2) 
Original list: [[], [], [], 'Red', 'Green', [1, 2], 'Blue', [], []] After deleting the empty lists from the said lists of lists ['Red', 'Green', [1, 2], 'Blue']

Flowchart: Remove empty lists from a given list of lists.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

How to delete a file or folder?

  • os.remove() removes a file.
  • os.rmdir() removes an empty directory.
  • shutil.rmtree() deletes a directory and all its contents

Path objects from the Python 3.4+ pathlib module also expose these instance methods:

  • pathlib.Path.unlink() removes a file or symbolic link.
  • pathlib.Path.rmdir() removes an empty directory.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Python remove empty elements from list | Example code

The easiest way is list comprehension to remove empty elements from a list in Python. And another way is to use the filter() method. The empty string «» contains no characters and empty elements could be None or [ ], etc.

Python remove empty elements from a list Example

Using list comprehension

Simp;e iterate through the list and add the non-empty elements.

list1 = ['A', ' ', ' ', 'B', ' ', 'C'] res = [ele for ele in list1 if ele.strip()] print(res) list2 = [1, 6, [], 3, [], [], 9] res = [ele for ele in list2 if ele != []] print(res) 

Python remove empty elements from list

Using filter() method

Just filter out the None and empty element form list.

If None is used as the first argument to filter() , it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

list2 = [1, 6, [], 3, [], [], 9] res = list(filter(None, list2)) print(res) 

Output: [1, 6, 3, 9]

Use a for loop to remove empty strings from a list

Iterate through the list and check if each string is not an empty string. If it is not an empty string, then add each non-empty string to an initially empty list using the append method.

list1 = ['A', ' ', ' ', 'B', ' ', 'C'] res = [] for i in list1: if i.strip() != '': res.append(i) print(res) list2 = [1, 6, [], 3, [], [], 9] res = [] for i in list2: if i: res.append(i) print(res) 

If you want to get rid of everything that is “falsy”, e.g. empty strings, empty tuples, zeros, you could also use

list2 = [x for x in list1 if x]

Do comment if you have any doubts and suggestions on this Python List topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

Читайте также:  Python модуль os walk
Оцените статью