l = [1,2,"hello","world"]
tup = ("jody",32)
print(l)
[1, 2, 'hello', 'world']
print(tup)
('jody', 32)
l = [1,2,3,4]
l[3] = 40
print(l)
[1, 2, 3, 40]
tup = (1,2,3,4)
print(tup)
(1, 2, 3, 4)
# add elements
new_tup = tup+(5,)
print(new_tup)
(1, 2, 3, 4, 5)
l.append(5)
print(l)
[1, 2, 3, 40, 5]
l = []
l.append('hello')
# 片切操作
l = [1,2,3,4]
print(l[1:3])
tup = (1,2,3,4)
print(tup[1:3])
[2, 3]
(2, 3)
#嵌套
l = [[1,2,3],[4,5]]
tup = ((1,2,3),(4,5,6))
print(l)
print(tup)
[[1, 2, 3], [4, 5]]
((1, 2, 3), (4, 5, 6))
# 相互转换
print(list((1,2,3)))
print(tuple([1,2,3]))
[1, 2, 3]
(1, 2, 3)
#内置函数
l = [3,2,3,7,8,1]
#统计3的数量
print(l.count(3))
2
#找到7的下标
print(l.index(7))
3
# 反转list
l.reverse()
print(l)
[3, 2, 3, 7, 8, 1]
#排序(ASC)
l.sort()
print(l)
[1, 2, 3, 3, 7, 8]
tup = (3,2,3,7,8,1)
print(tup.count(3))
2
print(tup.index(7))
3
print(list(tup))
print(list(reversed(tup)))
[3, 2, 3, 7, 8, 1]
[1, 8, 7, 3, 2, 3]
print(sorted(tup))
[1, 2, 3, 3, 7, 8]
print(sorted(l))
[1, 2, 3, 3, 7, 8]
# print(tup.sort()) wrong code
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-34-10257b8d26da> in <module>
----> 1 print(tup.sort())
AttributeError: 'tuple' object has no attribute 'sort'
# 列表和元组的存储差异
l = [1,2,3]
tup = (1,2,3)
print(l.__sizeof__())
64
print(tup.__sizeof__())
48
l = []
print(l.__sizeof__())
40
l.append(1)
print(l)
print(l.__sizeof__())
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
240
l.append(2)
print(l.__sizeof__())
240
l.append(3)
print(l.__sizeof__())
240
l.append(4)
print(l.__sizeof__())
240
l.append(5)
print(l.__sizeof__())
240
l.append(6)
print(l.__sizeof__())
240
l.append(7)
print(l.__sizeof__())
240
l.append(8)
print(l.__sizeof__())
240
l.append(9)
print(l.__sizeof__())
240
l.append(10)
print(l.__sizeof__())
320
标签:__,.__,tuple,tup,list,print,sizeof,append
From: https://www.cnblogs.com/ukzq/p/17189776.html