TheChetan
TheChetan

Reputation: 4596

Using ternary operator in python?

Consider the following code snippet. It flags a syntax error at 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 do I fix this?(I want to still use the ternary operator)

Upvotes: 7

Views: 5724

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You cannot use break in Your loop logic can be re written using itertools.takewhile if you want a more succinct solution

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

from itertools import takewhile

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

You can also remove the need for the else using a for loop by reversing your logic, check if j is not in dummy breaking when that is True:

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

Also if you want to remove all occurrences of any of the initial elements from digits that are in dummy, remove won't do that for any repeating elements but using a list comp after creating a set of elements to remove will:

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)

You can also iterate over a string so no need to call list on digits unless you plan on doing some list operations with it after.

Upvotes: 3

Ian
Ian

Reputation: 30813

Edit:

(see my conversation with Stefan Pochmann in the comments)

Ternary operator is not for only statement, but rather for assignment or for expression (and break is an only statement):

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

use normal if-else statement to do statements:

if cond:
    do()
else:
    break

Upvotes: 6

Related Questions