0

Given this code:

import random

plusMin = [1000, -47, 1000, -250, 1015, -63, 1000, -563]

masterList = []
subset = [-125, 375, 250, 250]

for item in plusMin:
    if item > 0:
        masterList.append(subset)
        subset.append(1)
    else:
        masterList.append(item)

print masterList

Shouldn't the following output?

[[-125, 375, 250, 250], -47, [-125, 375, 250, 250, 1], -250, [-125, 375, 250, 250, 1, 1], -63, [-125, 375, 250, 250, 1, 1, 1], -563]

...appending a "1" to the subset with each repetition of the for loop?

Instead the output I get is:

[[-125, 375, 250, 250, 1, 1, 1, 1], -47, [-125, 375, 250, 250, 1, 1, 1, 1], -250, [-125, 375, 250, 250, 1, 1, 1, 1], -63, [-125, 375, 250, 250, 1, 1, 1, 1], -563]

which looks like the output from nested for loops. Why on earth am I getting four "1" appended to the end of subset with the very first item in the for loop?

Thanks!

1 Answers1

0

You should do this

masterList.append(subset[:])

When you do masterList.append(subset) you're passing a reference to the subset. So each time you're doing this, you simply pass multiple references of the same list and at the end when you do a print, all the subsets evaluate to be the final value of subset.

subset[:] makes a copy of the list at the time of append.

Obsidian
  • 515
  • 3
  • 10
  • Thank you! This works beautifully. I don't quite understand why this works and my version didn't though... What do you mean by "a value reference"? –  Feb 16 '16 at 18:46
  • When you do `masterList.append(subset)` you're passing a reference to the subset. So each time you're doing this, you simply pass references of whatever is stored in `subset` and at the end when you do a print all the subsets are pointing to the same list. `subset[:]` makes a copy of the list at the time of append, like a frozen copy of the value. – Obsidian Feb 16 '16 at 18:53