user3787457
user3787457

Reputation: 93

How to select a few items from the list in python?

I have a scenario like

 log=[None]*4

and then based on certain conditions i'm inserting a value at one of the None position in log list. Suppose

log=[Begin,None,None,None]

Now i want to get only

log=[Begin]

and that too not using index as per my code whenever/wherever there is None it'll insert value How to do this. I have tried list comprehension but i think 'not in' doesn't work in that.

wal=[log[i] for i not in [None]]

Upvotes: 2

Views: 247

Answers (1)

timgeb
timgeb

Reputation: 78690

If I understand you correctly, you want a list of elements from log which are not None. You can get this list by issuing

 mylist = [x for x in log if x]

Or, if there could be values other than None in log which evaluate to False in a boolean context and you want these values in your new list:

 mylist = [x for x in log if x is not None]

Demo:

>>> log
[None, '', None, 1]
>>> [x for x in log if x]
[1]
>>> [x for x in log if x is not None]
['', 1]

Upvotes: 4

Related Questions