faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 14 people (79%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Removing null items from a list
Why not just loop through the list, test for false, and if false remove from the list?

Jul 5th, 2000 10:03
Nathan Wallace, unknown unknown, Bill Anderson, Hans Nowak, Snippet 334, Andrew M. Kuchling


"""
Packages: basic_datatypes.lists
"""
"""
> So I've got a very simple desire: to remove all false (I.E. None, 0, '',
> []) items from a list.
The filter() built-in function, when not passed a specific function,
does exactly this:
"""
print filter(None, [ 1,2,0, None, [], '12', '' ])
# [1, 2, '12']
"""
filter(F, seq) returns all the elements of the sequence 'seq', for
which the function F returns true: for example, the following code 
takes all the strings of even length:
"""
print filter(lambda s: len(s) % 2 == 0, ['a', 'ab', '', 'abcd'])
# ['ab', '', 'abcd']
"""
If F is None, then filter() simply returns those elements that Python
treats as true.
"""