-1

One of the problems in my curriculum states to create a function that returns a copy of a list with the non-true elements removed. After reviewing the solution, I didn't understand the meaning of this line of code in the solution:

   [val for val in lst if val]

I understand loops and if statements, however this does not make sense to me. I have not been able to find anything within my curriculum about this or the internet. If anyone understands and can explain, I would appreciate it. The entire function solution is below

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']
    """

    return [val for val in lst if val]
  • What part do you not understand? The comment tells you the overall effect. List comprehensions are documented very well. "Truthy" evaluation is documented very well. – Prune Sep 17 '20 at 20:49
  • The words are `ternary operator` and `list comprehension` if you want to read up on them. –  Sep 17 '20 at 20:50
  • 1
    Google "list comprehension", that's what it's called. – Alex Hall Sep 17 '20 at 20:50
  • Check this out: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python – CryptoFool Sep 17 '20 at 20:50
  • 1
    @hippozhipos that's not a ternary expression. – Alex Hall Sep 17 '20 at 20:50
  • Read about list comprehension. Just google it. In this case it append to list and return each element from the incoming list that match the condition - in this case when the element is True. – Yossi Levi Sep 17 '20 at 20:50
  • Note that Python has its own tutorial pages, this is the one which applies here: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions (the proposed duplicate is practically a variant of it) – tevemadar Sep 17 '20 at 20:51
  • @Alex Hall Isn't the syntax "statement if condition else otherStatement" a ternary operator in python? –  Sep 17 '20 at 20:52
  • @hippozhipos Yes, and where do you see that in the OP's code? – blhsing Sep 17 '20 at 20:53
  • @hippozhipos yes, and there's no `else` here. – Alex Hall Sep 17 '20 at 20:53
  • I mean yh, but when i was learning if statements on the same line as statement, it didn't really make sense to me until i read what ternary operators are, so i though it would help him as well. –  Sep 17 '20 at 20:54
  • Thanks for help for those who did! Just needed some direction since it is my 3rd day into Python. Will look into list comprehension. – personwholikestocode Sep 17 '20 at 21:14

1 Answers1

1
new_list = [val for val in lst if val]

Assigns a result to new_list using a list comprehension and is functionally equivalent to:

new_list = []
for val in lst:
    if val:
        new_list.append(val)

So all list elements, that are not True are filtered out.

You can find a good explanation about list comprehensions here

Yannick Funk
  • 1,319
  • 10
  • 23