Using ternary operator in python?

Consider the following code snippet. It puts a syntax error in the break statement.

digits = list(str(102))
dummy = list(str(102/2))
for j in digits:
    dummy.remove(j) if j in dummy else break

How to fix it? (I want to use the ternary operator)

+4
source share
2 answers

Edit:

(see my conversation with Stefan Pochmann in the comments)

The ternary operator is not only for the operator, but rather for assignment or for expression (and breakis the only statement):

a = 5 if cond else 3 #OK
do() if cond else dont() #also OK
do() if cond else break #not OK

use statement if-elsefor operators:

if cond:
    do()
else:
    break
+5
source

You cannot use break in. Loop logic can be rewritten with itertools.takewhile if you want a more concise solution

digits = list(str(102))
dummy = list(str(102/2))

from itertools import takewhile

for d in takewhile(dummy.__contains__, digits):
    dummy.remove(d)

else, for, , , j , :

for j in digits:
    if j not in dummy:
        break
    dummy.remove(j)

, , , remove , comp :

digits = str(102)
dummy = list(str(102/2))
st = set(takewhile(dummy.__contains__, digits))
dummy[:] = [d for d in dummy if d not in st]

print(dummy)

, , .

+2

All Articles