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'
Asked By: ibra

||

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
Answered By: ibra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.