Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select non empty elements of list in Python [duplicate]

Given:

a = 'aaa'
b = ''
c = 'ccc'
d = ''
e = 'eee'

list = (a, b, c, d, e)

How can I get a string using all the non empty elements of the list ?

Desired output:

'aaa,ccc,eee'
like image 986
hernanavella Avatar asked Jan 30 '23 05:01

hernanavella


1 Answers

Using a generator expression:

",".join(string for string in lst if len(string) > 0)

The ",".join() part is using the join() method of strings, which takes an iterable argument and outputs a new string that concatenates the items using "," as delimiter.

The generator expression between parenthesis is being used to filter empty strings out of the list.

The original list doesn't change.

like image 92
slezica Avatar answered Jan 31 '23 19:01

slezica