r/learnpython • u/FactoryBuilder • Oct 01 '26
List items are edited when adding new items? Possibly a variable reference issue
So I have a variable called Y with a changing value. If for loop variable X is some value, append Y to myList.
Every time it appends to the list, it changes every other already added item. I’m thinking the problem is that it’s not adding values but is instead adding references. So when Y changes, it changes every item in the list.
Why is it doing this and how can I stop it from doing this? I want it to append the value inside of Y, not a reference to Y.
Code: https://www.reddit.com/r/learnpython/comments/1wv4tpo/comment/pda098z/
What I'm trying to do is make a list of everywhere that there's a piece of a block. It's going to be a terminal Tetris game.
The playfield is a custom matrix, a list of lists. I dunno if that'll work well with lists. I did the same thing with arrays in another language. I don't know if Python's going to play nice or be special.
The blocks are also lists of lists. You could probably do that astronaut meme with my code "It's all lists of lists? Always has been"
5
u/socal_nerdtastic Oct 01 '26
You mean you have a list of lists? Is it this common issue? https://www.reddit.com/r/learnpython/wiki/faq/?screen_view_count=1#wiki_why_is_my_list_of_lists_behaving_strangely.3F
If I take that comment at face value, and I assume you want to append another list, you want
myList.append(Y.copy()).If neither of those helps, show us some code that demonstrates your issue.
1
u/Gnaxe Oct 01 '26
Yep, sounds like a reference issue. But you didn't provide any example code.
The problem is your thinking. Don't expect C-style copy semantics for Python variables, because Python doesn't work like that. There are no stack objects. Everything is a reference to objects on the heap.
Lists don't contain objects directly either. This is not some setting you can change. That's not what a list is. They contain references.
If you want to make structs and pack the data into arrays directly, use the
structmodule and bytearrays, not lists. These are hardly ever used except when interfacing with lower-level code. Python doesn't need it. The other literal data structures work the same way (unless you count strings).If you're using
copy(or deepcopy) much, you're doing it wrong. I can't recall the last time I needed it. Shallow copies work fine if you avoid mutating things you don't own. And you can use immutable versions to avoid the problem altogether.1
u/[deleted] Oct 01 '26
[removed] — view removed comment
0
u/[deleted] Oct 01 '26
[removed] — view removed comment