Be careful!

The list of list is modified unexpected, python

# code patch A:
list = [1,2,3,4,5,6,7]
print('list A :', list)
for i in list:
temp = i
if i > 5:
temp = i + 10000
print('list A\':', list) # code patch B:
list = [[1],[2],[3],[4],[5],[6],[7]]
new_list = []
print('\nlist B : ',list)
for i in list:
temp = i # will this allocate a new RAM space for var 'temp'?
if i[0] > 5:
temp[0] = i[0] + 1000
new_list.append(temp)
print('list B\': ', list, end='')
print(' <-- you can see the list is changed, which is not i want.')
print('new_list:', new_list) # code patch C:
list = [[1],[2],[3],[4],[5],[6],[7]]
new_list = []
print('\nlist C : ',list)
for i in list:
temp = [''] # only this line is MODIFIED than code patch B.
temp[0] = i[0]
if i[0] > 5:
temp[0] = i[0] + 1000
new_list.append(temp)
print('list C\': ', list, end='')
print(' <-- you can see the list is NOT changed.')
print('new_list:', new_list) '''
Output:
---
list A : [1, 2, 3, 4, 5, 6, 7]
list A': [1, 2, 3, 4, 5, 6, 7] list B : [[1], [2], [3], [4], [5], [6], [7]]
list B': [[1], [2], [3], [4], [5], [1006], [1007]] <-- you can see the list is changed. which is not i want.
new_list: [[1], [2], [3], [4], [5], [1006], [1007]] list C : [[1], [2], [3], [4], [5], [6], [7]]
list C': [[1], [2], [3], [4], [5], [6], [7]] <-- you can see the list is NOT changed.
new_list: [[1], [2], [3], [4], [5], [1006], [1007]] Question:
why list B' is modified in the for loop? '''

最新文章

  1. [转]MySQL: Starting MySQL….. ERROR! The server quit without updating PID file
  2. hdu3847Trash Removal(凸包)
  3. 小波说雨燕 第三季 构建 swift UI 之 UI组件集-视图集(三)Activity Indicators视图 学习笔记
  4. python数字图像处理(4):图像数据类型及颜色空间转换
  5. windows常见已知熟悉操作命令
  6. ROS主题发布订阅
  7. WCF入门教程一[什么是WCF]--转载只为学习收藏
  8. 判断是否是IP地址
  9. LeetCode_Scramble String
  10. 解决Xcode7之后发送网络请求http格式不支持报错问题
  11. MySQL PHP 语法
  12. 我的第一个SpringProject——HelloWorld
  13. sklearn的kmeans测试
  14. ajax请求,函数外无法获取请求的数据问题解决
  15. Java生成短链接
  16. 《Linux 性能及调优指南》写在后面的话
  17. artTemplate子模板include
  18. 关于Oracle与MySQL的使用总结
  19. Linux(CentOS)系统下搭建svn服务器
  20. zoj-3410-Layton&#39;s Escape

热门文章

  1. 【洛谷P4445 【AHOI2018初中组】报名签到】
  2. Gradel 多渠道打包 代码混淆
  3. leetcode 720. 词典中最长的单词
  4. 用流的方式来操作hdfs上的文件
  5. curl 使用 post 请求,传递 json 参数,下载文件
  6. Powershell 邮件发送
  7. rac节点挂掉后,vip飘到别的节点,但是业务连接不上报 no listener问题处理
  8. Node.js实战9:用EventEmitter触发和响应事件。
  9. Java-集合第五篇Map集合
  10. python 二维数组转一维数组