0

I'm writing some code for a bioinformatics library in Python 3.9.4

def immediate_neighbors(seq):
    neighborhood = [seq]
    for i, ntide in enumerate(seq):
        for other_ntide in ['A', 'C', 'G', 'T']:
            if ntide != other_ntide:
                neighbor = seq
                neighbor[i] = other_ntide
                neighborhood.append(neighbor)
                print(seq)
    return neighborhood

When I input ['C', 'A', 'A'] I get the output

['A', 'A', 'A']
['G', 'A', 'A']
['T', 'A', 'A']
['T', 'C', 'A']
['T', 'G', 'A']
['T', 'T', 'A']
['T', 'T', 'C']
['T', 'T', 'G']
['T', 'T', 'T']
[['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T'], ['T', 'T', 'T']]

The print(seq) was put there just for debugging purposes. The original variable seq is clearly being written over, but I can't figure it how this is happening.

jojeyh
  • 276
  • 1
  • 3
  • 12
  • 1
    `neighbor = seq` does not make a copy, it refers to the same list. That is why seq is being modified – shriakhilc Dec 31 '21 at 02:55
  • 1
    Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – shriakhilc Dec 31 '21 at 02:56
  • Yes that's exactly what I needed, thank you – jojeyh Dec 31 '21 at 02:57

0 Answers0