Skip to main content
 首页 » 编程设计

python之元组在 Python 中真的是不可变的吗

2024年10月24日13birdshome

<分区>

我今天遇到的一个问题,它实际上测试了 Python 中元组的不变性:

  • Interviewer: Are tuples immutable in Python?

  • Me: Yes

  • Interviewer: So what does print(t1) here print?

    t1 = (4, 5) 
    t1 = t1 + (91, 10) 
    print(t1) 
    
  • Me: (4, 5, 91, 10)

  • Interviewer: How does immutability of tuple then define this behavior?

  • Me: It's got nothing to do with immutability, t1 label is referring to a new tuple.

  • Interviewer:

    >>> t = (1, 2, [3, 4])  
    >>> t[2] += [5, 6] 
    

    What will happen next?

  • Me: TypeError is raised

  • Interviewer: What will be the value of t be after that?

  • Me: (1, 2, [3, 4]) or (1, 2, [3, 4, 5, 6]) maybe, not sure

  • Interviewer: What made you think the value will change to (1, 2, [3, 4, 5, 6]) and what will happen if I write

    >>> t[2] = t[2] + [5, 6] 
    

    will t2 still be (1, 2, [3, 4, 5, 6]) after this operation?