nanalltat
nanalltat

Reputation: 13

How to keep the empty element in a list using list comprehension in Python?

ls=['ISSN1','94500','2424922X','','21693536','01464116','16879724','22042326','07419341','09272852','00015903','0324721X','']
ls = [i.zfill(8) for i in ls if i != ""]
ls

Output:
['000ISSN1',
 '00094500',
 '2424922X',
 '21693536',
 '01464116',
 '16879724',
 '22042326',
 '07419341',
 '09272852',
 '00015903',
 '0324721X']

However, this removed the empty element. I tried several other ways to keep the empty element:

method 1:

for i in range(len(ls)):
    if ls[i]!="":
        ls[i]=str(ls[i]).zfill(8)
    else:
        pass
    
ls

method 2:

def changes(ls):
    for i in range(len(ls)):
        if ls[i]!="":
            ls[i]=str(ls[i]).zfill(8)
        else:
            pass
    return ls

ls=changes(ls)
ls

Both methods return me with the desired output:

['000ISSN1',
 '00094500',
 '2424922X',
 '',
 '21693536',
 '01464116',
 '16879724',
 '22042326',
 '07419341',
 '09272852',
 '00015903',
 '0324721X',
 '']

I'm still wondering if there is a way to achieve the same result with list comprehension?

Upvotes: 1

Views: 430

Answers (3)

user2390182
user2390182

Reputation: 73450

You can use a conditional expression (a if condition else b) within the comprehension:

ls = [i.zfill(8) if i else i for i in ls]

Note that this shortens if i != "" to if i as only the empty string is false in a boolean context.

For your particular case, you could also use some trickery (using the fact that True == 1, False == 0) to keep it even shorter:

ls = [i.zfill(8*bool(i)) for i in ls]

Upvotes: 1

Lumber Jack
Lumber Jack

Reputation: 622

You just have to add a 'else' in your code.

ls=['ISSN1','94500','2424922X','','21693536','01464116','16879724','22042326','07419341','09272852','00015903','0324721X','']
ls = [i.zfill(8) if i != "" else '' for i in ls]
ls

OUTPUT:

enter image description here

Upvotes: 0

balderman
balderman

Reputation: 23815

see below

ls = ['ISSN1', '94500', '2424922X', '', '21693536', '01464116', '16879724', '22042326', '07419341', '09272852',
      '00015903', '0324721X', '']
ls = [i.zfill(8) if i else i for i in ls]
print(ls)

output

['000ISSN1', '00094500', '2424922X', '', '21693536', '01464116', '16879724', '22042326', '07419341', '09272852', '00015903', '0324721X', '']

Upvotes: 0

Related Questions