首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券