Tricks in Python

阅读本文大约需要2分钟

Python code shows as follows:

What will happen after the operation ?

A、list1 = (1,[2,3,6,7],(4,5));

B、Error

C、Both

Think for a while, and the right answer is C.

But why?

Dissemble the program and you will know the process.

STEP 1: get the list (list1[1])

STEP 2: revise the list in-place

STEP 3: return the new tuple element into object

STEP 4: for tuple is an immutable object, a Type Error is thus triggered

However, its member (list1[1]) has already modified

We can examine the explanation by id()

The similar trick also applies to copy.

Function parameters should also be carefully used.

Summary:

For mutable objects, changes happen in-place (with the same id)

eg,list

For immutable objects, create, initialize and then set value (id changes)

eg,number, tuple

往期文章

联系我

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181105G0WEG100?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券