I want to generate list of 100 copies of the same sentence with one char modified in each copy. I am currently learning python and I don’t understand why something like this:
def generate_copy(seq):
copies = [seq for i in range(100)]
for copy in copies:
copy[random.randint(0, len(seq) - 1)] = random.choice(char_list)
print(''.join(copy))
return copies
modifies all copies. I want to get something like this: [‘AAAB’, ‘BAAA’, ‘ZAAA’, …], like they are independent from each other, but I get: [‘AAAB’, ‘ZAAB’, ‘ZCAB’, …]. How can I do it?
>Solution :
Not sure how did you get result you pasted – string in python is immutable. copies is list of strings. So copy is string. You cannot type copy[0] = 'a' as you will get TypeError: 'str' object does not support item assignment cause of that.
What do you want to do is build changed sequence when you create copies.
def change_random_letter(seq, char_list):
i = random.randint(0, len(seq) - 1)
new_letter = random.choice(char_list)
return f"{seq[:i]}{new_letter}{seq[i+1:]}"
def generate_copy(seq):
copies = [change_random_letter(seq, char_list) for _ in range(100)]
return copies
EDIT: I noticed you pass list as seq. If so, copies are not a copies! Look
l = [1, 2]
ll = [l, l]
ll[0][0] = "A"
print(ll) # [['A', 2], ['A', 2]]
When type is mutable, by using a variable you use the reference. So all copies elements points to the same place in memory. You need to use copy function of list.
copies = [seq.copy() for _ in range(100)]