1
def compact(word):
    holder = []
    for i in word:
        if i is True:
            holder.append(i)
    return holder


print(compact([0, 1, 2, 3, False, ""]))

I am a python beginner and this is the code I have written to append the list "holder" with only true values. So the list should contain only 1, 2, 3. However when I run this code the output is only an empty list []. I'm sorry if this is a dumb question but I am trying to understand where I am going wrong.

  • 2
    you want to check simply `if i`. Your items are integers, which **are not True**. Try running the line `1 is True` in the interpreter and see what you get – Tomerikoo Dec 17 '19 at 20:47
  • 2
    Neither of the objets `1`, `2`, nor `3` `is False`. It sounds like you want *truthy* values, using `is` checks for identity with the singleton `True` object. Just use `if i:` Note, you can sue the built-in `list(filter(None, [0, 1, 2, 3, False, ""]))` for this. When you pass `None` as the predicate, it filters on truthiness – juanpa.arrivillaga Dec 17 '19 at 20:48
  • 1
    @juanpa.arrivillaga is there a functional difference for using `None` as the key in `filter` over `bool`? – C.Nivs Dec 17 '19 at 20:54
  • 1
    @C.Nivs no, there isn't as far as I am aware – juanpa.arrivillaga Dec 17 '19 at 20:57
  • 2
    @C.Nivs Actually I believe passing `None` and `bool` are exactly equivalent here https://stackoverflow.com/questions/49009870/what-are-the-differences-between-bool-and-operator-truth#comment97974258_49009871 – Chris_Rands Dec 17 '19 at 20:58

2 Answers2

3

ints are never True, but they can be logically True - any non-0 int has a logical value of True, which is fundamentally different to int is True. Have a look at this for an explanation of the is operator.

You can also cut down your code by using list comprehensions:

lst = [0, 1, 2, 3, False, ""]
compacted = [n for n in lst if n]
Ed Ward
  • 2,333
  • 2
  • 10
  • 16
0

if i: will do the trick since it returns False for i = 0 or '', or False


Solution 1: Use list comprehension:

input_list = [0, 1, 2, 3, False, ""]
output_list = [i for i in input_list if i]

output_list
[1, 2, 3]

Solution 2: If you really need the function, use this:

def compact(word):
    holder = []
    for i in word:
        if i:
            holder.append(i)
    return holder

print(compact([0, 1, 2, 3, False, ""]))
[1, 2, 3]
seralouk
  • 30,938
  • 9
  • 118
  • 133