0

I'm initializing these two lists and trying to replace the first 3 items in each list in two different ways.

b = c = [2, 4, 6, 8, 10, 12]
print(b)
b[0] = 3; b[1] = 6; b[2] = 9
print(b)
c[0:2] = [3,6,9]
print(c)

but when I run the code I get the weird output below. I get what i expect for "b" but something totally expected for "c". Can someone explain to me why this is happening?

b = [2, 4, 6, 8, 10, 12]
c = [2, 4, 6, 8, 10, 12]
new b = [3, 6, 9, 8, 10, 12]
new c = [3, 6, 9, 9, 8, 10, 12]
  • 1
    `[0:2]` is only two items. Do you want `[0:3]`? Note that at all times `c==b` – Adam Smith Apr 27 '20 at 03:06
  • This is a common beginner mistake in Python. Assigning a list to a variable does *not* copy the list. It merely creates a new *reference* to the list. Any changes to the list are reflected in all references to it. If you want to avoid that, you need to copy the list. If you print `b` again after changing `c`, you'll see that it has changed as well, and that they are both the same. – Tom Karzes Apr 27 '20 at 03:07
  • 1
    @TomKarzes while true, that doesn't actually appear to be the behavior he's noticing. – Adam Smith Apr 27 '20 at 03:07
  • @TomKarzes of course they are, but the behavior he's noticing is that `c[0:2]` is only two elements large, while he's trying to replace it with a list of length 3. I think the other behavior will bite him pretty immediately once he gets this working, but it's hard to say. – Adam Smith Apr 27 '20 at 03:11
  • 1
    @AdamSmith Yes, agreed. The range is off by one. There are really two problems with the code. – Tom Karzes Apr 27 '20 at 03:12
  • @TomKarzes assuming OP is doing what we think he's doing, yes :-) – Adam Smith Apr 27 '20 at 03:12
  • I got it, thanks guys! – JustAGirlCoding Apr 27 '20 at 05:09

1 Answers1

1

c[0:2] means the first two elements, so essentially you're replacing [3, 6] with [3, 6, 9]. You should use

c[0:3] = [3, 6, 9]
c = [3, 6, 9, 8, 10, 12]
Shubham Sharma
  • 714
  • 1
  • 8
  • 18