除list.copy()外,列表方法均不会改变列表的id,也不会创建列表,list.copy()
Type Markdown and LaTeX: α2α2
[x*x for x in range(6) if x % 2 == 0]
[0, 4, 16]
[x for x in [1,2,3,4,5] if x < 3]
[1, 2]
x = [3,5,3,7]
[x.index(i) for i in x if i==3]
[0, 0]
{1,2,1}
{1, 2}
{1,‘a’,True}
{1, ‘a’}
{1.2,True}
{True, 1.2}
set(‘hello’)
{‘e’, ‘h’, ‘l’, ‘o’}
a = 2
a = a + 3
a
5
aList = [3,4,5]
id(aList)
1862326273608
aList[1] = 6
aList
[3, 6, 5]
s = ‘Happy new year to you!’
id(s)
1862326281464
s=s.replace(‘you’,‘us’)
print(s)
Happy new year to us!
id(s)
1862326281608
a = [1,2,3]
b = a
id(a)
1862326275400
id(b)
1862326275400
a[0]=6
print(a)
[6, 2, 3]
print(b)
[6, 2, 3]
a = [1,2,3]
b = a[:]
id(a)
1862326275784
id(b)
1862326187208
s = [1,2,3]
a = s
s.append(5)
print(s,a)
[1, 2, 3, 5] [1, 2, 3, 5]
s = [1,2,3]
a = s[:]
s.append(5)
print(s,a)
[1, 2, 3, 5] [1, 2, 3]
a = [[1,2,3],[4,5,6]]
b = a.copy()
b
[[1, 2, 3], [4, 5, 6]]
b[0][1] = 7
b
[[1, 7, 3], [4, 5, 6]]
a
[[1, 7, 3], [4, 5, 6]]