Interview Python I think everyone will be asked a question, what is the difference between a list and a tuple in python?
In general, I will answer that the list element is mutable, the tuple element is immutable (as in the book or any other blog), in general, the interviewer will not ask, however ... Today's interviewer asked me, "really immutable?" Is nothing going to change?
I didn't react at that time, so I said it was immutable. Interviewer Oh, and asked the tuple can add, I replied: Yes, but will produce a new tuple (this I also answer good, secretly happy)
Then the interviewer asked, "Can I delete it?" I actually do not know, because I did not delete, however, the tuple element is immutable this sentence I directly simply replied that can not be deleted, and then I checked a bit, really can not delete.
Summarize the basic points of attention and usage of the meta-group
Tuples we use the most should be the function of the arguments, as well as the function to return it.
1. Tuple immutability Verification:
A = (up to)
A[0] = 2 will error TypeError: ' Tuple ' object does not the support item assignment.
A = (1,2,[1,2,3])
A [2][1] = 0 is OK
Description: The tuple element is immutable, the data that the element points to is immutable a[0] = 2 error, is a[0] This reference points to the 2 is the int data, the int data itself is not mutable, Python str,int,char,tuple itself is immutable, list,dict variable.
A[2][1] is mutable because this reference points to a list,list that is mutable, so there is no error when changing.
Take a look at an excerpt from the online map:
So the tuple constant is pointing, pointing to what has always been, cannot change
2. The addition of tuples
A = (() ID (a): 3052812140L
b = (3,4)
A = a+b ID (a): 153147604 the ID of each person must be different, this should have no objection ...
At this point a = (1,2,3,4). Not that the tuple immutable, how changed, but actually a to a and B to add the tuple, not a changed. The original tuple has not changed, there is no reference, waiting to be used as garbage collection.
3. The deletion of tuples
Tup = (1,2,3,4);
Del Tup[0];
This will cause an error TypeError: ' Tuple ' object doesn ' t support item deletion
4. Tuple access and slicing
A = (1,2,[3,4])
A[0] point to 1,a[2][1] point to 4
A[:1] point to a sub-tuple
5. Tuple operations
CMP (Tuple1, Tuple2): Compares two tuple elements.
Len (tuple): counts the number of tuple elements.
Max (tuple): Returns the maximum value of an element in a tuple.
Min (tuple): Returns the minimum value of an element in a tuple.
Tuple (seq): Converts a list to a tuple.
CMP (), Len (), Min (), Max () are the built-in functions of the sequence, and the tuple is also a sequence, so you can use built-in functions to manipulate
Tuple () is a factory function
Wipe, this next interview ask the tuple should not have a problem ...
Python tuple (tuple)