Tuple slicing not returning a new object as opposed to list slicing

后端 未结 4 1010
抹茶落季
抹茶落季 2021-02-19 14:18

In Python (2 and 3). Whenever we use list slicing it returns a new object, e.g.:

l1 = [1,2,3,4]
print(id(l1))
l2 = l1[:]
print(id(l2))

Output

4条回答
  •  天命终不由人
    2021-02-19 14:58

    It's an implementation detail. Because lists are mutable, l1[:] must create a copy, because you wouldn't expect changes to l2 to affect l1.

    Since a tuple is immutable, though, there's nothing you can do to t2 that would affect t1 in any visible way, so the compiler is free (but not required) to use the same object for t1 and t1[:].

提交回复
热议问题