I get TypeError: choice() got an unexpected keyword argument 'k' , when using python random.choice
Question:
I want to generate a random string of length n, on a given alphabet.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet) for x in range(n)) ) # work fine
print(''.join(random.choice(alphabet, k=n))) # doesn't work
The error:
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: choice() got an unexpected keyword argument 'k'
Answers:
The correct method is choices with s, so use random.choices
.
The mistake come from the two function that have similar names. The first is random.choices
with s, and the second one is random.choice
without s.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet, k=n))) # gives an error
print(''.join(random.choices(alphabet, k=n))) # the correct method, work fine
I want to generate a random string of length n, on a given alphabet.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet) for x in range(n)) ) # work fine
print(''.join(random.choice(alphabet, k=n))) # doesn't work
The error:
Traceback (most recent call last):
File "<input>", line 3, in <module>
TypeError: choice() got an unexpected keyword argument 'k'
The correct method is choices with s, so use random.choices
.
The mistake come from the two function that have similar names. The first is random.choices
with s, and the second one is random.choice
without s.
import random
alphabet = "ACTG"
n= 10
# print(''.join(random.choice(alphabet, k=n))) # gives an error
print(''.join(random.choices(alphabet, k=n))) # the correct method, work fine