One of a1, a2 or a3 is given as a value while other are empty. If I want to print out only a given value, what would you like to write your code? Thank you so much in advance.
Example,
a1=empty
a2=5
a3=empty
a=[a1,a2,a3]
print(a)
a=5
One of a1, a2 or a3 is given as a value while other are empty. If I want to print out only a given value, what would you like to write your code? Thank you so much in advance.
Example,
a1=empty
a2=5
a3=empty
a=[a1,a2,a3]
print(a)
a=5
Empty values in python are None
. So maybe something like this:
a1 = None
a2 = 5
a3 = None
a = [a1,a2,a3]
def get_value(L):
return [x for x in L if x is not None][0]
a = get_value(a)
print(a)
output:
5
Update: This could fail if there is no value in the list a
, so we should include exception handling for this case:
def get_value(L):
try:
return [x for x in L if x is not None][0]
except IndexError:
return None
Try this:
[e for e in a if e][0]
Since non-empty values are the same as True.
You could also use:
[a.remove(None) for e in a.count(None)]
a[0]
Try using short-circuit property:
print(a1 or a2 or a3)
Only the one different than None will be the result.