Randomizing a list of 25 things using Python

I got tagged in the oh-so popular “25 Random Things” meme on Facebook. To make a point that I sometimes think in code and I don’t think its weird, I wrote the script below to randomize my list before I posted it.


import random

f = open('25-things.txt')
list = f.readlines()
"""Magnus L Hetland's solution http://bit.ly/uN4iq"""
result = []

for i in range(len(list)):
    element = random.choice(list)
    list.remove(element)
    result.append(element)

i = 1
for line in result:
    print "%s. %s" % (i, line)
    i += 1
Advertisements

8 thoughts on “Randomizing a list of 25 things using Python

  1. @amanda – open a text file that has 25 Random Things about sean, randomize the order of those things, then print out the randomized list (and number them), The result us the Facebook note you saw….

  2. @Pithywit – yep, looks like random.shuffle(list) would be the succinct way to go. I found core part of the script above at the that bit.ly address. I just noticed now that it was written in 1999 so it’s pre-python 1.6 and might have been pre 1.5.2 when random.shuffle was introduced.

  3. That’s one of the lovely things about python–how often you can discover a one-liner or built-in function that does exactly what you want…

  4. random.shuffle(list) doesn’t work with nested lists, at least when I tried with something like this:

    [[‘books’, 3], [‘toys’, 5]]

    The above code did and only adds three lines to my script.

    Thanks for posting this.

  5. Pingback: Past taglines for tmrs « The Monkey Represents Sharing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s