- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
First Non-Empty String in list in Python
Given a list of strings, lets find out the first non-empty element. The challenge is – there may be one, two or many number of empty strings in the beginning of the list and we have to dynamically find out the first non-empty string.
With next
We apply the next function to keep moving to the next element if the current element is null.
Example
listA = ['','top', 'pot', 'hot', ' ','shot'] # Given list print("Given list:\n " ,listA) # using next() res = next(sub for sub in listA if sub) # printing result print("The first non empty string is : \n",res)
Output
Running the above code gives us the following result −
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
With filer
We can also achieve this using the filter condition. The filter condition will discard the null value and we will pick up the first not null value. Only with python2.
Example
listA = ['','top', 'pot', 'hot', ' ','shot'] # Given list print("Given list:\n " ,listA) # using filter() res = filter(None, listA)[0] # printing result print("The first non empty string is : \n",res)
Output
Running the above code gives us the following result −
Given list: ['', 'top', 'pot', 'hot', ' ', 'shot'] The first non empty string is : top
- Related Articles
- List of non-empty tables in all your MySQL databases?
- First non-repeating in a linked list in C++
- Python Program to Remove the nth Index Character from a Non-Empty String
- Get a list of non-empty tables in a particular MySQL database?
- From a list of IDs with empty and non-empty values, retrieve specific ID records in JavaScript
- Detecting the first non-repeating string in Array in JavaScript
- How to remove an empty string from a list of empty strings in C#?
- How to create an empty list in Python?
- Empty List in C#
- First non-repeating character using one traversal of string in C++
- Finding the first non-repeating character of a string in JavaScript
- Query non-empty values of a row first in ascending order and then display NULL values
- How to check if a list is empty in Python?
- Looping in JavaScript to count non-null and non-empty values
- Python | Remove empty tuples from a list

Advertisements