18.104.22.168 create a tuple;
Python. Tuples (Кортежи)
We already know collections such as lists, sets, and strings.
Tuples are very similar to lists; they are also an indexed collection, only they use parentheses instead of square ones (and can often be omitted):
Comparisons of tuples
Tuples can be compared with each other
Note that the operations == and != are applicable to any tuple, regardless of the element types. But operations <, >, <=, >= are applicable only in the case where corresponding elements are tuples of one type. Therefore, it is possible to compare ('12', 'school') and ('12', 'class'), but tuples (1, 2) and ('5', 'Amir') cannot be compared - the Python interpreter will generate an error. In this case, the comparison occurs sequentially element by element, and if the elements are equal, the next element is viewed.
The most important technical difference between tuples and lists is immutability. As with a string, an element cannot be added to a tuple using the append method, and an existing element cannot be modified by indexing it. This looks like a disadvantage, but later on, we will understand that tuples have advantages.
There is also a semantic, that is, semantic, difference. Suppose lists are more likely to combine an indefinite number of homogeneous entities. In that case, a tuple is a quick way to connect several different objects with different meanings under one name.
In the example above, the card tuple consists of two elements, indicating the value and its suit. Another nice difference between tuples and lists is that they can be elements of a set:
Tuples can be assigned to each other. This is what makes Python's beautiful feature, the view construct, work
As you know, to the left of the assignment sign there = must be a variable name or the name of a list with an index or several indexes. They indicate where to "put" the value written to the right of the assignment sign. However, to the left of the assignment sign, you can also write a tuple of such designations (roughly speaking, variable names), and to the right, a tuple of values that should be placed in them. The values on the right are specified in the same order as the variables on the left (here the parentheses around the tuple are optional):
In the example above, we made the tuple to the right of =, right on the same line. But you can prepare it in advance:
The best part: first, all the values on the right are calculated, and only then they are put into the left side of the assignment operator. Therefore it is possible, for example, to swap the values of the variables a and b, writing: a, b = b, a.
The example below will print "1 2 3". Make sure you understand why.
With tuples, many algorithms are magically concise. For example, calculating Fibonacci numbers:
|Просмотров: 200 | ||
|Всего комментариев: 0|