Python Forum

Full Version: Newbie query regarding lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am just working through some intros to Python. Basically I read about a concept and then have a play around to make sure I understand it. Right now, I'm on lists.

I wrote the following program to test a few commands:
test_list = [1,2,3,4]
print (test_list[0])
print (test_list[2])
print (test_list[-1])
sub_test_list = test_list[1:3]
print (sub_test_list)
naturals = [0,1,2,3,4,5,6,7,8,9,10,11,12]
evens = naturals[2::2]
print(evens)
odds = naturals[1::2]
print(odds)
primes = odds
primes[4:6]=[11,13]
print(odds) # OP originally had this bolded
print(primes)
naturals.append(13)
print(naturals)
The bit that confused me is the command 'print(odds)' towards the bottom in bold. I was still expecting odds to be [1,3,5,7,9,11] as the change was applied to the list 'primes'. However, both 'odds' and 'primes' were printed as [1,3,5,7,11,13].

Please could someone explain to me why this is the case?

Thanks

Stephen
On line 12, the assignment reuses the same object. It's not a copy. So when one is modified, so is the other. You can make a "shallow" copy by replacing line 12 with
primes = odds[:]
This works because with [:] the variable "primes" no longer refers to the same object.
Thank you very much
Can I follow up with one additional question? I appreciate how to fix my initial query, but am not sure why the assignment in the original code reuses the object whereas in the code below it appears not to.

x=8
print('x=',x)
z=x
print('x=',x)
print('z=',z)
z=z+2
print('x=',x)
print('z=',z)
i.e. when z is modified x remain unmodified.

I assume it is that
variable2 = variable1
assigns variable2 independent to variable1 going forward (just of identical value at this stage) whereas
datatype2 = datatype1
assigns datatype2 and datatype1 to be identical going forward such that changes to one are automatically applied to the other.

However, I'd like to be 100% sure before moving on.
Great question. Basically, lists are mutable, meaning can be edited. Numbers cannot change, though the variable that points to a number can be changed to point to a new number, which is what happens in your code. For this issue you've run into with lists, you won't run into with immutable types like numbers, tuples and frozensets.
Thanks again. Want to spend time getting the basics right before moving on (and only installed Python on Thursday!)