Is it possible to do this on one line in Python?
if <condition>:
myList.append('myString')
I have tried the ternary operator:
myList.append('myString' if <condition>)
but my IDE (MyEclipse) didn't like it, without an else
.
Is it possible to do this on one line in Python?
if <condition>:
myList.append('myString')
I have tried the ternary operator:
myList.append('myString' if <condition>)
but my IDE (MyEclipse) didn't like it, without an else
.
Yes, you can do this:
<condition> and myList.append('myString')
If <condition>
is false, then short-circuiting will kick in and the right-hand side won't be evaluated. If <condition>
is true, then the right-hand side will be evaluated and the element will be appended.
I'll just point out that doing the above is quite non-pythonic, and it would probably be best to write this, regardless:
if <condition>: myList.append('myString')
Demonstration:
>>> myList = []
>>> False and myList.append('myString')
False
>>> myList
[]
>>> True and myList.append('myString')
>>> myList
['myString']
E701 multiple statements on one line
so also non-pythonic... ;) –
Interference <condition> and (strng = 'myString')
–
Otilia objects/dictionaries
in the condition: x = object['attribute'] or None
will throw a KeyError
exception if there is no attribute
key in object. The correct way will still be: x = object['attribute'] if 'attribute' in object else None
–
Contretemps x = object.get('attribute')
in that case –
Principle The reason the language doesn't allow you to use the syntax
variable = "something" if a_condition
without else
is that, in the case where a_condition == False
, variable
is suddenly unknown. Maybe it could default to None
, but Python requires that all variable assignments actually result in explicit assignments. This also applies to cases such as your function call, as the value passed to the function is evaluated just as the RHS of an assignment statement would be.
Similarly, all return
s must actually return, even if they are conditional return
s. Eg:
return variable if a_condition
is not allowed, but
return variable if a_condition else None
is allowed, since the second example is guaranteed to explicitly return something.
continue if i == 0
in a for loop. –
Caliper else pass?
–
Sergiosergipe else pass
doesn't work because the ternary expression should return a value that can be passed to return
. pass
is not a valid return
value. –
Hurtado if a_condition: variable = "something"
and if a_condition: return variable
are legal. So it is essentially an arbitrary syntactic choice of python. –
Otilia mylist.append("hi") if append_smth == True
–
Lauricelaurie if <condition>: myList.append('myString')
Otherwise, no. Why the need to put it on one line?
Note that the "ternary operator" is an operator. Like any operator, it must return something, so how can you have a ternary operator without the else
clause? What is it supposed to return if the condition isn't true-like?
You are basically asking for do_thing() if <condition> else pass
construct (which will throw SyntaxError
, if ran). As I have discovered during research for (somewhat) similar question do_thing() if condition else None
is as close as you can get (which is just another way to do <condition> and do_thing()
). So, to summarize this idea and other answers, here are your options:
if <condition>: myList.append('myString')
— seems to be the least 'hacky' (and thus preferred) way<condition> and myList.append('myString')
myList.append('myString') if <condition> else None
i’d just do this if i wanna add optional elements to a list based on a condition.
nums = [
1,
2,
3 if <condition> else None,
4,
]
# nums now contains values of `None`, so we delete all occurrences of `None`
nums.remove(None)
this just replaces the value with None if the condition is not met and then later, it just redefines the list without the None Values. this way they preserve their index if the condition is met
nums.remove(None)
–
Unremitting myList.extend(['myString'] if condition else [])
would also work, though it's more work than the other solutions.
You can do something like below. Note that None
is never at any point appended to myList
.
myList.append('myString') if <condition> else None
Also, Python should accept the one-liner below.
if <condition>: myList.append('myString')
myList.append('myString') if True else _
But if you're not assigning to anything, doesn't matter. I'm concerned about this person attempting a list-comprehension with similar logic though. –
Pyretic For all those people asking: "Why would you want to do that?", there is one case where that syntax would be extremely useful.
Take this code:
class a:
def calla(self):
print("a")
class b:
def callb(self):
print("b")
def c(*args):
class c(a if args[0], b if args[1]):
def __init__(self, *args):
self.calla = getattr(self, "calla", None)
if callable(self.calla):
self.calla()
self.callb = getattr(self, "callb", None)
if callable(self.callb):
self.callb()
return c(args[2:])
C = c(False, False)
The code is attempting to conditionally inherit class a and/or/nor b. The getattr and callable lines check whether the method from class a or b exists, i.e. whether the classes were sucessfully inherited. The factory function is used to define the conditions for inheritance that are given to class c. And lastly, there are the conditions inside the definition of class c's inheritance.
Unfortunately this code doesn't run as there must be an else after the if... It cannot be avoided using a one line if statement either as starting with "if" is invalid syntax.
You also cannot else inherit object like this:
class c(a if args[0] else object, b if args[1] else object):
This code could throw an error of inheriting "object" twice if neither a or b need to be inherited. ("else None" and "else c" dont work either ofcourse)
Therefore the way to avoid it is by creating throwaway classes for a and b with nothing inside but this looks terrible and seems wrong...
class a:
def calla(self):
print("a")
class b:
def callb(self):
print("b")
class empty:
pass
class empty2:
pass
def c(*args):
class c(a if args[0] else empty, b if args[1] else empty2):
def __init__(self, *args):
self.calla = getattr(self, "calla", None)
if callable(self.calla):
self.calla()
self.callb = getattr(self, "callb", None)
if callable(self.callb):
self.callb()
return c(args[2:])
C = c(False, False)
So it would be useful to have the ternary operator not require else.
def map_key_vs_values(db, key_name, val_name):
_map = {}
for item in db:
p = item[key_name]
a = item[val_name]
try: a not in _map[p] and _map[p].append(a)
except: _map[p] = [a]
return _map
© 2022 - 2024 — McMap. All rights reserved.