Learn Python tuples with a bit of simplicity

  • 2020-04-02 14:07:39
  • OfStack

In terms of tuples, we talked about this term in the last lecture. This lecture is going to cover it in its entirety.

Here's an example:


>>># Variable reference str
>>> s = "abc"
>>> s
'abc'

>>># If I wrote it this way, it would be ...
>>> t = 123,'abc',["come","here"]
>>> t
(123, 'abc', ['come', 'here'])

The variable t, as seen in the above example, does not report an error or "last valid," but instead assigns the object to the variable t as a new data type: tuple.

Tuples are enclosed in parentheses, with elements separated by commas. (both English half corners)

A tuple is a sequence type of data, similar to list/ STR. Its feature is that its elements cannot be changed, which is different from list but similar to STR. Its elements can be any type of data, which is the same as list, but different from STR.


>>> t = 1,"23",[123,"abc"],("python","learn")  # Element diversity, near list
>>> t
(1, '23', [123, 'abc'], ('python', 'learn'))

>>> t[0] = 8                  # Cannot modify in situ, near str
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> t.append("no") 
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
  >>> 

From the simple comparison above, it seems that a tuple is a hybrid product that combines the properties of part list and part STR. That makes sense.

Access the elements and slices as a list

Let's review a few things from the list:


>>> one_list = ["python","qiwsir","github","io"]
>>> one_list[2]
'github'
>>> one_list[1:]     
['qiwsir', 'github', 'io']
>>> for word in one_list:
...   print word
... 
python
qiwsir
github
io
>>> len(one_list)
4

So let's see if we can replace this list with a tuple


>>> t
(1, '23', [123, 'abc'], ('python', 'learn'))
>>> t[2]
[123, 'abc']
>>> t[1:]
('23', [123, 'abc'], ('python', 'learn'))
>>> for every in t:
...   print every
... 
1
23
[123, 'abc']
('python', 'learn')
>>> len(t)
4

>>> t[2][0]   # You can do that. Oh yeah, list You can do the same thing in China 
123
>>> t[3][1]
'learn'

All methods that modify a list in a list, in a tuple, fail.

The transformation of list() and tuple() can be achieved respectively:


>>> t     
(1, '23', [123, 'abc'], ('python', 'learn'))
>>> tls = list(t)              #tuple-->list
>>> tls
[1, '23', [123, 'abc'], ('python', 'learn')]

>>> t_tuple = tuple(tls)          #list-->tuple
>>> t_tuple
(1, '23', [123, 'abc'], ('python', 'learn'))

Where is a tuple used?

Since it's a heterozygosy of list and STR, what does it do? Isn't it ok to use both list and STR?

In many cases, it is possible to use both list and STR. However, don't forget that the problems we solve in computer languages are not always simple problems. Just like in our natural languages, although some words seem to be dispensable and can be replaced by others, we still need to use them in some situations.

It is generally believed that a tuple has these characteristics, and this is where it is used:

Tuples operate faster than lists. If you define a constant set of values, and the only thing you need to do with it is iterate over it, use a tuple instead of a list.
If you "write protect" data that doesn't need to be modified, you can make your code more secure. Using a tuple instead of a list is like having an implicit assert statement that this data is constant. If you have to change these values, you need to perform a tuple to list transformation (using a special function).

Tuples can be used as keys in dictionaries, but not lists. Actually, it's more complicated than that. A Dictionary key must be immutable. The Tuple itself is immutable, but if you have a Tuple of a list, it's considered mutable, and it's not safe to use as a dictionary key. Only strings, integers, or other dictionary-safe tuples can be used as dictionary keys.
Tuples can be used in string formatting, which we'll use later.


Related articles: