Emiel.s
Emiel.s

Reputation: 937

Python: how to sort random numbers in list

I am making an program that simulates the roll of a dice 100 times. Now I want to sort the output of the random numbers that are given by the program. How do I have to do that?

import random

def roll() :
    print('The computer will now simulate the roll of a dice 100 times')
    list1 = print([random.randint(1,6) for _ in range(100)])

roll()

Upvotes: 0

Views: 15438

Answers (3)

Anand Jambhulkar
Anand Jambhulkar

Reputation: 31

The above problem can also be solved using for loop as follows -

>>> import random

>>> mylist = []

>>> for i in range(100):
        mylist.append(random.randint(1,6))


>>> print(mylist)

To sort the list, issue the following commands -

>>> sortedlist = []
>>> sortedlist = sorted(mylist)
>>> print(sortedlist)

Upvotes: 2

tommy.carstensen
tommy.carstensen

Reputation: 9622

If you don't need the original list:

list1.sort()

If you need the original list:

list2 = sorted(list1)

See python.org: http://wiki.python.org/moin/HowTo/Sorting/

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121744

You do not have a list. The print() function returns None, not whatever it just printed to your terminal or IDE.

Store the random values, then print:

list1 = [random.randint(1,6) for _ in range(100)]
print(list1)

Now you can just sort the list:

list1 = [random.randint(1,6) for _ in range(100)]
list1.sort()
print(list1)

Upvotes: 4

Related Questions