in python a = a[:] why?? | Sololearn: Learn to code for FREE!

+6

in python a = a[:] why??

# this came as challenge on sololearn # please explain a = [1,2,3] print(a,a[:]) print(a is a[:]) # False But Why ?? https://code.sololearn.com/cPm2dkq5GS0i/?ref=app

5/2/2021 7:19:57 PM

WÊΠÅÐÑÄŃ

3 Answers

New Answer

+15

a == a[:] and a is a[:] The "is" operator compares the identity of two objects while the "==" operator compares the values of two objects. "is" will return True if two variables point to the same object and "==" if the objects referred to by the variables are equal.

0

Hi! It is important to understand the different between = and == (assignment vs equality). Let L = [0, 1, 1, 2, 3, 5, 8] be a list. Then L[start:stop:step], where start, stop and step are integers, gives a list slice of the list L. The slice can contain from no element [] to include all of L:s element in the list, depending on the given indices. You can read about it or try to change the indices to you understand how it work. So L[:] gives a list with all elements in L, but it copy the element to a new list. L[:] looks like L (when you print them) but they’re acctually different lists. Let L2 = L[:] and change a element in L2 by L2[0] = 88. You will now see that L and L2 are different lists; L will still be unchanged, but L2 have changed. Printing L and L2 give: L = [0, 1, 1, 2, 3, 5, 8] L2 = [88, 1, 1, 2, 3, 5, 8] So they have, as Dragon Wolf stated, different addresses in memory; so L2 is not L. L2 = L[:] is a simple way to make a (shallow) copy the list L, instaed of using L2 = L.copy().

-1

'is' operator functionality is to compare the address of variables The above example 'a' id and 'a[:]' id two variables pointing to different ID's so the answer is False '==' operator to compare the variable values the above example 'a' value and 'a[:]' value both values are same so answer is True