Short syntax for if true then break [duplicate] - python

This question already has answers here:
fit "break IF condition" statement into one line
(3 answers)
Closed 4 months ago.
I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition
for _ in range(10):
if condition:
break
...
I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError.
What are Python's options for one-line conditioning, except if condition: break?

You could use itertools.takewhile to combine aspects of a for and while loop, moving the (negated) break condition to the loop's head. The condition in the lambda can use both variables from the enclosing scope and the current item from the iterable.
from itertools import takewhile
for x in takewhile(lambda x: not condition, iterable):
...
However, while this is shorter (at least in terms of lines), I would not consider it more readable. I would just stick with the explicit break.

Related

Is there a way to find out which condition (out of many by using or) in "if" is evaluated to true because of which it entered inside the if? [duplicate]

This question already has answers here:
Python - How to find which condition is true in if statement?
(6 answers)
Closed 8 months ago.
I have an if statement, let's say:
if cond1 or cond2 or cond3:
do_something()
Can I find out which among these three conditions (cond1,cond2 and cond3) was true because of which it entered inside and executed do_something()?
P.S: I'm looking for answers which doesn't suggest me to use another 2 if's below my if to find out which was true.
You could do it in a for loop:
for i, j in enumerate((cond1, cond2, cond3)):
if j:
do_something()
print(i) #Do whatever you want to do with the 1st condition that was true
break

method in Python similar to myArray.remove("john") and case insensitive [duplicate]

This question already has an answer here:
How do I remove words from a List in a case-insensitive manner?
(1 answer)
Closed 4 years ago.
is there a way in Python to remove all matches of a name, but make it case insensitive, similar to: myArray.remove("john") ? i want to remove all instances of John and john from the array without having to write out a loop
You can't use remove for this, but you can easily write your own function that does it manually.
For example:
def remove_ci(lst, s):
s = s.casefold()
for i, elem in enumerate(lst):
if elem.casefold() == s:
del lst[i]
return
raise ValueError('remove_ci(x): x not in list')
Or, if you'd rather do it by copying rather than in-place mutation:
def removed_ci(iterable, s):
s = s.casefold()
for elem in iterable:
if elem.casefold() == s:
yield from iterable
return
yield elem
raise ValueError('removed_ci(x): x not in iterable')
(You can make the second version a lot more concise with itertools.takewhile, but probably better to write out the loops and comparisons explicitly the first time you need to do something like this.)
Your question says you "want to remove all instances of…" But that's not what list.remove does; it removes only the first instance, and it raises an exception if there are no instances.

doing "nothing" in else command of if-else clause [duplicate]

This question already has answers here:
Using statements on either side of a python ternary conditional
(4 answers)
Closed 4 years ago.
Code:
for i in range(1000):
print(i) if i%10==0 else pass
Error:
File "<ipython-input-117-6f18883a9539>", line 2
print(i) if i%10==0 else pass
^
SyntaxError: invalid syntax
Why isn't 'pass' working here?
This is not a good way of doing this, if you see this problem the structure of your code might not be good for your desires, but this will helps you:
print(i) if i%10==0 else None
This is not a direct answer to your question, but I would like suggest a different approach.
First pick the elements you want to print, then print them. Thus you'll not need empty branching.
your_list = [i for i in range(100) if i%10]
# or filter(lambda e: e%10 == 0, range(100))
for number in your_list:
print number

Return conditional statements to new line when organizing code(Python)? [duplicate]

This question already has answers here:
Styling multi-line conditions in 'if' statements? [closed]
(30 answers)
Closed 8 years ago.
So I know when listing variables in object class, you can return every line to list the variables vertically for better organization:
class Thing(object):
def __init__(x,
y,
z):
Is it possible to do the same thing with conditionals in an if statement, like so?
if condition1 and
condition2 and
condition3:
Obviously that's probably not the right syntax for it since it doesn't work, but it's a good example of what I'm trying to do in order to organize my code so I don't have scroll to right when something has long names for conditional satements.
Parentheses to the rescue!
if (1 == 1 and
2 == 2 and
3 == 3):
# ...

How to condense if/else into one line in Python? [duplicate]

This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed last month.
How might I compress an if/else statement to one line in Python?
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
Python's if can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Only for using as a value:
x = 3 if a==2 else 0
or
return 3 if a==2 else 0
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.

Categories