Random sequences in Python
Section 4 April 2nd, 2007There is a reason to say that Python has batteries included. On the last post we have seen a small example of randomization in Python, generating random integer values for a (extremely) simple dice game. We move to another example, still simple which will allow us to generate random DNA sequences. The script is
#!/usr/bin/env python
import random
import sys
length = int(sys.argv[1])
dnaseq = list('ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT')
result = ''
for i in range(length):
result += random.choice(dnaseq)
print result
Not fancy at all, just plain simple (yet again). We import a couple of modules, sys and random, and ask for the sequence length as a script parameter. dnaseq is a list containing a tandem repeat of ACGT, and from there we will extract our random nucleotides. In fact dnaseq could have been ‘ACGT’ only. The fact that we create a string and convert it to a list, is just for convenience of writing 'ACGT...' easier than ['A', 'C' ...]. We then declare an empty string that will be used to store the random sequence. And inside the loop, the command that does all the magic: random.choice(<list>). This command will return a random element from the list passed as subject. Using it inside a loop we will get a random nucleotide on each iteration and add it to our string.
This is a very simple command, but at the same time extremely powerful and easy to implement. A good exercise from this would be to modify the dnaseq string and see if there is any change in the final random sequence.
October 24th, 2007 at 10:31 am
Hi Paulo:
Thanks for the introduction of ‘random’ module, that I’m not familiar with.
But I have a question about ‘random.choice()’ function. Is not the random.choice() equivalent with random.choice()? So is it necessary for converting string to list in the above code?
Thanks!
Dilmurat
October 24th, 2007 at 11:43 am
Hi Dilmurat,
In fact it is not necessary to convert from string to list. I just used the conversion to show that random.choice() can use either. Sometimes your elements will be in a string, sometimes in a list.
Paulo
April 20th, 2008 at 9:28 am
Shorter version using list comprehensions
—
#!/usr/bin/env python
import random,sys
length = int(sys.argv[1])
print “”.join([random.choice('ACGT') for x in range(lenght)])
—
look at this I just got a new snake subspecie! arrrghh…
June 8th, 2008 at 9:41 pm
Here is code that how we random a list:
from random import randrange
lstSeed=['a','b','c','d','e']
results=[]
while lstSeed:
pos = randrange( len(lstSeed) )
results.append(lstSeed[pos])
del lstSeed[pos]
print lstSeed
return results