0

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 the oddOrEven list has the word 'even' appended to it
  • When i is odd, the 'odd' list within the oddOrEven 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?

SuperHanz98
  • 2,090
  • 2
  • 16
  • 33
  • 2
    Actually, i wished they didn't close this question. Your making a shallow copy when you *2, try oddOrEven = [[],[]] and it will work – oppressionslayer Nov 14 '19 at 18:25
  • 1
    Just finished writing an answer, can't post. See here for best description: https://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists – smiller Nov 14 '19 at 18:28
  • 1
    oddoreven = [[] for i in range(2)].just create a list using this.everything else remain same in your code – ksouravdas Nov 14 '19 at 18:31
  • Thanks guys, would accept your answers if you were allowed to answer -__-. Have some votes instead. – SuperHanz98 Nov 14 '19 at 19:29

0 Answers0