I've got a problem with a project I'm working on. I've managed to discover that the problem is actually with how I thought list appending works in Python. I've recreated the problem I'm having in my project as this much smaller snippet:
Let's say you have the following code:
# A list of two lists (one for even one for odd)
oddOrEven = [[]] * 2
for i in range(5):
if i % 2 == 0:
oddOrEven[0].append("even")
else:
oddOrEven[1].append("odd")
print(oddOrEven)
Now what I would expect to happen:
- When
i
is even, the 'even' list within theoddOrEven
list has the word 'even' appended to it - When
i
is odd, the 'odd' list within theoddOrEven
list has the word 'odd' appended to it
So I expect the output to look like this:
[['even', 'even', 'even'], ['odd', 'odd']]
However, what is actually output is this:
[['even', 'odd', 'even', 'odd', 'even'], ['even', 'odd', 'even', 'odd', 'even']]
I just can't get my head around how this works. When something is appended to one sub-list, it's also appended to the other? The loop only runs 5 times, and yet 10 append operations are occurring.
Can someone explain why this happens, but also how I can achieve what I expected the result to be using the same list structure?