Python, difference between two ways for removing last elem of list
2015-08-30 12:42
549 查看
For immutable variable, python is pass-by-value. Actually, python will create a new instance for immutable variable. But for mutable variable, python is pass-by-reference.
I found list = list[0:-1], python will create a new sublist, but for list.pop(), it will not.
Here is an example.
The output is
In this example, id() function is used to identify object. It is an integer which is guaranteed to be unique and constant for this object. We could think of it as the memory address.
We can find, in this example, the lst = lst[0:-1] give rise to the change of address of lst. The original list a is not affected.
Output is
We notice that, for list.pop(), python will not alter the address of list.
I found list = list[0:-1], python will create a new sublist, but for list.pop(), it will not.
Here is an example.
Example 1
[code]a = [1,2,3] print id(a) def func(lst): print id(lst) lst = lst[0:-1] pritn lst, id(lst) func(a) print a, id(a)
The output is
[code]4147851564 4147851564 [1, 2] 4147852172 [1, 2, 3] 4147851564
In this example, id() function is used to identify object. It is an integer which is guaranteed to be unique and constant for this object. We could think of it as the memory address.
We can find, in this example, the lst = lst[0:-1] give rise to the change of address of lst. The original list a is not affected.
Example 2
[code]a = [1,2,3] print id(a) def func(lst): print id(lst) lst.pop() print lst, id(lst) func(a) print a, id(a)
Output is
[code]4147933484 4147933484 [1, 2] 4147933484 [1, 2] 4147933484
We notice that, for list.pop(), python will not alter the address of list.
相关文章推荐
- python需要注意的语法
- python执行时出现的问题
- 【Python】笔记:类继承问题总结
- selenium +python+eclipse+pydev环境搭建
- multiprocessing在python中的高级应用-IPC 之 Queue
- 学习日志---python(新式类,面向对象)
- Python getopt模块
- 5.Python的Queue模块
- python 排序归纳
- 一个简单的程序,统计文本文档中的单词和汉字数,逆序排列(出现频率高的排在最前面)。python实现。
- python代码风格指南:pep8 中文翻译
- python中的传值和传引用
- 一步步学习Python-django开发-建立django数据库
- 使python程序更优美的小技巧
- multiprocessing在python中的高级应用-进程
- Python实现抓取页面上链接
- 零基础学python-9.4 对象的真值
- 零基础学python-9.4 对象的真值
- 零基础学python-9.3 对象的比较
- 零基础学python-9.3 对象的比较