Search code examples
pythonpython-3.xfor-looplist-comprehension

How do I convert this Python for loop into a list comprehension


I am writing code to randomly roll a die and then return the amount of times each number is rolled.

I got this to work as a function, but I want to know how I could convert this to a list comprehension.

This is the function I am using:

results = []
for roll_num in range(1000):
    result = die.roll()
    results.append(result)

Note that roll() is a method I made in a class for a die.

The closest I get for a working list comprehension is:

result = die.roll()
results = [result for value in range(1000)]

which does roll the die but it only rolls one number 1,000 times instead of six numbers a random amount adding up to 1,000 times.

So can this for loop be to turned into a list comprehension, if so how?


Solution

  • Seems like you have it?

    results = [random.randint(1,6) for value in range(10)] works, so

    results = [die.roll() for value in range(1000)] should as well.

    The only problem is you had assigned die.roll(), which resulted in result being the primitive return value rather than a function call.