mslee017
mslee017

Reputation: 59

Appending To a New List In Python If Value Is True

I'm trying to create a function which returns a copy of a list with the non true elements removed. I tried to go at it like this:

def compact(lst):
"""Return a copy of lst with non-true elements removed.

    >>> compact([0, 1, 2, '', [], False, (), None, 'All done'])
    [1, 2, 'All done']
"""
new_list = []
for element in lst:
    if element == True:
        new_list.append(element)

return new_list 

However when using the provided test:

compact([0, 1, 2, '', [], False, (), None, 'All done'])

It only returns [1] rather than the expected [1,2,'All Done']. If I simply remove the conditional the function will print every value, so seemingly something is off with the logic checking if something is a True value.

Upvotes: 0

Views: 1920

Answers (1)

user1717828
user1717828

Reputation: 7225

Just remove the == True from your code:

def compact(lst):
    """Return a copy of lst with non-true elements removed.
    
    >>> compact([0, 1, 2, '', [], False, (), None, 'All done'])
    [1, 2, 'All done']
    """
    new_list = []
    for element in lst:
        if element:
            new_list.append(element)

    return new_list 
    
compact([0, 1, 2, '', [], False, (), None, 'All done'])

To see why, try running code like 1 == True and 2 == True.

Upvotes: 1

Related Questions