Random numbers to items in a list - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Random numbers to items in a list

The_BulletThe_Bullet Posts: 2Member
Very new to programming here (understatement) and am enjoying learning as I go and problem solving. I have been playing around with random numbers and have no problem (as yet) using them in a program. However, I would like to know if there is a way to asign a random number to each of the items in a list. Thus- for example 8 items in a list would be each assigned an indivual random number from 1 to 8.
Thank you

Comments

  • infidelinfidel Posts: 2,900Member
    : Very new to programming here (understatement) and am enjoying learning as I go and problem solving. I have been playing around with random numbers and have no problem (as yet) using them in a program. However, I would like to know if there is a way to asign a random number to each of the items in a list. Thus- for example 8 items in a list would be each assigned an indivual random number from 1 to 8.

    Glad to have you on board. Python is a great language.

    Python comes with a very capable randomness module already. All you have to do is "import random". Here is a quick example of how to do what you ask. I recommend reading the module documentation yourself. If you're on Windows, go to Start->Programs->Python x.y->Python Manuals
    and then click on "Global Module Index". There you'll find all the standard stuff that Python comes with.

    [code]
    >>> import random
    >>> l = []
    >>> for i in range(8):
    ... l.append(random.randint(1,8))
    ...
    >>> l
    [8, 3, 6, 7, 4, 1, 6, 5]
    >>>
    [/code]

    Let me know if you have any other questions or if this code snippet didn't make sense to you.


    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

  • The_BulletThe_Bullet Posts: 2Member
    Thanks for the reply. Yes, that's great, and as usual (for me at least :) ) a few simple logical lines of instructions suffice where I would usually write reams and reams to get an inferior result. My main problem was ensuring that each list item was given a "different" random number, and this does just that.
    Thanks
  • infidelinfidel Posts: 2,900Member
    : Thanks for the reply. Yes, that's great, and as usual (for me at least :) ) a few simple logical lines of instructions suffice where I would usually write reams and reams to get an inferior result. My main problem was ensuring that each list item was given a "different" random number, and this does just that.

    Glad to help. This board has very little traffic, so anything you need help with I'd be glad to take a look at.


    [size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

Sign In or Register to comment.