0

I have a list of characters, and for each character I need to update a list based on the character. The list represents a 2D vector, and I would like to save each vector to a list to keep track of every iteration. If there are duplicates I dont need to worry about it, I just have to see which ones came up. So, here's what Im working with:

dir_list = [] #this list is populated by a txt file
vectors = []
main_vector = [1, 1]

for i in dir_list:        
    if(i == '^'):
        main_vector[0] += 1
        vectors.append(main_vector)       
    if(i == 'v'):
        main_vector[0] -= 1
        vectors.append(main_vector)        
    if(i == '>'):
        main_vector[1] += 1
        vectors.append(main_vector)        
    if(i == '<'):
        main_vector[1] -= 1
        vectors.append(main_vector)

print(main_vector)
print(vectors)

So the main_vector updates, and the vectors list gets the right number of entries, but theyre all the same - whatever main_vector ends up being. Ive tried appending differently, moving things around,

JonnyDoeInWisco
  • 233
  • 1
  • 4
  • 12
  • Also see [here](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python), [here](http://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference), and [here](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly). – TigerhawkT3 Dec 20 '15 at 01:38
  • Briefly: you just have a bunch of references to the same `list`. – TigerhawkT3 Dec 20 '15 at 01:39
  • And you can fix it by changing `main_vector = [1, 1]` to `a,b = 1,1`, then changing the `main_vector[0] += 1` to `a += 1` (for all similar lines), and `vectors.append(main_vector)` to `vectors.append([a,b])`. Alternatively, you could keep almost everything as it is and just do `vectors.append(main_vector[:])` to append a copy. – TigerhawkT3 Dec 20 '15 at 01:44
  • Noting how you repeat `vectors.append(main_vector)` four times, I'd say you have some refactoring to do, as well. – TigerhawkT3 Dec 20 '15 at 01:45
  • Ok, I used the slicing and that worked. I thought what I was doing was adding 1 to whichever position in the list and sending the updated list to the vectors list. I guess I'll have to read up on slicing, thanks. Should I delete this question? – JonnyDoeInWisco Dec 20 '15 at 01:58
  • You were updating the `list`, yes, but it also updated all the other references to that same `list`, because that's how mutable objects generally work. You can read the linked questions for more information. There's no need to delete this, but you may if you want to. – TigerhawkT3 Dec 20 '15 at 02:04

0 Answers0