My need is if the loop has no value then the value has to be 0, if there is any value then be the last value of the list collected in the loop:
response_json = response.json()
list_shots = response_json['content']['shotmap']['shots']
last_goal = [shot['min'] for shot in list_shots if shot['eventType'] == 'Goal']
Example result:
[15, 42, 65, 90]
So the final analysis would be:
if (len(last_goal) == 0):
last_goal = 0
elif (len(last_goal) > 0):
last_goal = last_goal[-1]
In this case the final value in last_goal would be:
90
Is there any way to reduce the number of lines of code needed to achieve this result?
I don’t know if there’s a way to set the values to be added in the same position [0] in the list instead of all being added in sequence.
Or is there a way to add 0 already in the initial list so that it is not necessary to use if - elif
>Solution :
How about using the ternary operator:
last_goal = 0 if not last_goal else last_goal[-1]