is there a way to explain the internal working of list comprehension for cases where there’s an if condition and the other where there’s only if condition?

['-'+i+'-' if int(i)%2==0 else i for i in str(num).strip('-')] works because of else. in this case it uses conditional expression[0], rather the normal syntax for comprehension lists. “A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses”[1]

The normal form is [expression_statement forloop if_filter], right? So instead of (2) you should have

[i for i in s if i in ar and ar[i]>4]

which it is equivalent with

alist = []
for i in s:
    if i in ar and ar[i]>4]:
        alist.append(i)

[0] https://docs.python.org/3/reference/expressions.html#conditional-expressions

[1] https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top