Python list depth copy and related actions

Source: Internet
Author: User
Tags shallow copy python list

1, shallow copy, if the source changes, p1[1][1], p2[1][1], person[1][1] will change together
Import Copy
person = [' name ', [' Saving ', 100]]
‘‘‘
P1 = copy.copy (person)
P2 = person[:]
P3 = List (person)
‘‘‘
P1 = person[:]
P2 = person[:]
Print (p1)
Print (p2)

P1[0] = ' Alex '
P2[0] = ' Fengjie '
Print (p1)
Print (p2)

P1[1][1] = ' 50 '
Print (p1)
Print (p2)

1, deep copy: Source changes, does not affect
Import Copy
Names2 = copy.deepcopy (names)
Print (names)
Print (Names2)
NAMES[2] = "Xiang Touch"
Names[3][0] = "ALEC"
Print (names)
Print (Names2)

3, tuples: Can not edit the list, other actions the same list
Names = (' Alex ', ' Jack ')

4. List operation
#列表类型
names = ["Zhangyang", "Guyun", "Xiangpeng", ["Alex", "Jack"], "Xulianghen"]
Names2 = ["1", "2", "3", "4"]
Print (names)
#print (Names[0]) #第一个位置
#print (Names[0],names[2])
#print (Names[1:3]) #切片, Gu Tou regardless of the tail
#print (names[1:]) #取从1到结束位置
#print (Names[-1]) #取最后一个
#print (Names[-2:-1]) #不包含最后一个值, Gu Tou regardless of the tail
#print (Names[:3]) #0可以忽略

#names. Append ("Leihaidong") #插入到最后面
#names. Insert (1, "Chenronghua") #插入到固定位置, you can insert only one

#names [2] = "Xiedi" #修改

#删除
#names. Remove ("Zhangyang")
#del Names[1]
#names. Pop (1) #不输入默认删除最后一个

#print (Names.index ("Guyun")) #找Guyun的下标
#print ( names[names.index ("Guyun"))
#统计Guyun个数
#print (Names.count ("Guyun"))
#names. Clear () #清空
#names. Reverse () #反转
#names. Sort () #排序
#names. Extend (names2) #扩展
#del Names2 #删除变量


Python list depth copy and related actions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.