Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

one line loop always adding values at index zero on list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading