background

See some students are very persistent use of tuple, remember when I first learned Python, also love tuple, why? Because I’ve never seen data like this before, (1,2), and it feels very special, and it’s nice to use it. I,j=(1,2), and all of a sudden you have two variables;

And if the function returns more than one value, it’s good to use a tuple, so it just returns and it’s easy to parse.

But why are tuples so good? Is it really that good? Why are tuples rarely used for json? I haven’t given it much thought.

explore

So I want to know, why do we design a tuple, how should we use it?

Why are there separate tuple and list data types

Write a general understanding:

Tuples are similar to lists, but their basic use is different.

Tuple’s design is similar to Pascal Records or C Structs (neither familiar…). ;

What is it?

  • A collection of related data
    • Small set size
  • These data can be of different types
    • But it adds up to a combination

A typical application is the Cartesian coordinate system, where (x,y,z) represents the coordinates of an object. It looks pretty intuitive, more intuitive than lists or dict.

Tuple is immutable, meaning that once a tuple is defined, its data cannot be changed. Such as:

>>> a = (1,2) >>> A [0]=3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> a[0] 1Copy the code

I defined a tuple a, I want to change its first value, but error ‘tuple’ object does not support item Assignment.

If you want to change it, you should define a list that is mutable, which is a mutable list.

summary

There are a few things that make tuple more enjoyable to use, in my own opinion:

  • Groups feel better, as they are designed,tupleIt’s a combination of several related things to represent something
    • My understanding is that this combination of things is something that has some concrete meaning, like cartesian coordinates
  • When parsing is convenient, such as the following, you can get two variables in one line of code
>>> i , j = (1, 2)
>>> i
1
>>> j
2Copy the code
  • Similarly, when designing a function that returns more than one variable, you can use itlistBut it can also be usedtupleWhen parsing, we have the convenience of the above one.
  • I should add, becausetupleimmutableSo it can be used as a dictkeyBecause of the dictionarykeyIs usedhashtableWhat is realized cannot (should) be changed.
  • What else? Not yet.

Where tuples are less recommended, the sense is more important:

  • tupleOnce you define it, you can’t change the values inside, so that’s inconvenient
  • iftupleIf there is no connection between the elements, it is missing the essence of the actual design. Right

reference

  • why are there separate tuple and list data types
  • why must dictionary keys be immutable?