randomize elements in a file or list using Python

Last week I had to populate a mysql table with some random user names. First problem was to get those names - which I managed writing a crawler with Python. Using the program I got a text file with around 500 names listed in alphabetical order. But I didn't want to insert those in the same order as it will look odd (you don't want to get a list of opponent player's name all starting with 'A' in a game, right?). Then I decided to write some python code to generate another file with names in random order. The logic will be simple. First load all the names in a list, and from that list get a random element and put in another list. Delete the element from the initial list. Before I started coding, I googled for a while and found an interesting solution!


import random
...
count = names.__len__()
# names is the list containing names in alphabetical order
names = random.sample(names, count)
# now names contain names in random order!
...


Another Python magic!

Comments

Paddy3118 said…
Hi,
Try looking up the docs on random.shuffle. It does what you want without needing the length.

Remember also that it does its work on the given list itself, in-place as it is called, so the function does not return a value - it just modifies the list you give it and returns None.

- Paddy.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code