0

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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
  • Thinking about the `collections.Counter` – Daniel Hao Dec 07 '21 at 21:18
  • 2
    Why did you put `result = die.roll()` outside the list copmrehension? In any case, yes, this can be directly converted, `[die.roll() for roll_num in range(1000)]`, although, in both the loop and the comprehension, `_` would idiomatically be used instead of `roll_num` for a variable that is not meant tobe used – juanpa.arrivillaga Dec 07 '21 at 21:20

2 Answers2

1

I think what you're looking for is:

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

Note that _ is commonly used as a stand-in for a value you don't really care about.

sloppypasta
  • 1,068
  • 9
  • 15
1

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.

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18