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

Add two external variables via list comprehension

im learning list comprehension but don’t know if i can add a sum two variables via list comprehension to a list.
So is it possible to express below code in a list comprehension?

#Make some rolls, and store the results in a list.
#die_1 & die_2 represent D6 dices, .roll() is a .choice() generated from import random

results = []

for roll_num in range(1_000):
    result = die_1.roll() + die_2.roll()
    results.append(result)

>Solution :

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

The most concise way of doing this would be:

results = [ die_1.roll() + die_2.roll() for _ in range(1_000) ]

For each of the 1000 iterations, both dice are rolled and their values are summed and stored in the list.

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