Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (18.4k points)

Trying to fill the empty nested lists with the value, I found there is distinct behavior between using the for loop vs list comprehension, and I was wondering why this is, despite functionally they should do the same. See below:

nl= [[True], []]

for item in nl:

    if len(item) ==0:

        item.append('false')

#this is the desired result

print(nl)

[[True], ['false']]

nl=[item.append('false') for item in nl if len(item)==0]

print(nl)

[None]

#no idea why this happens

print([item.append('false') for item in nl if len(item)==0]

print(nl)

[[True], ['false']]

1 Answer

0 votes
by (36.8k points)

It is because the item.append() does not return anything. The list comprehension is making this list of None.

You can change it to:

nl=[['false'] if len(item)==0 else item for item in nl]

Master end-to-end Data Science through Data Science Online Courses 

Browse Categories

...