Python 之 tuple

来源:互联网 发布:有mac版本的网游 编辑:程序博客网 时间:2024/05/25 05:36

Tuple is an immutable list.


  • Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
  • It makes your code safer if you "write−protect" data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that special thought (and a specific function) is required to override that.
  • Remember that I said that dictionary keys can be integers, strings, and "a few other types"? Tuples are one of those types. Tuples can be used as keys in a dictionary, but lists can't be used this way.Actually, it's more complicated than that. Dictionary keys must be immutable. Tuples themselves are immutable, but if you have a tuple of lists, that counts as mutable and isn't safe to use as a dictionary key. Only tuples of strings, numbers, or other dictionary−safe tuples can be used as dictionary keys.
  •  Tuples are used in string formatting.
Tuples can be converted into lists, and vice−versa.