Python Tuples and Sequences

Python Tuples and sequences


We saw that lists and strings have many common properties, such as sequencing and slicing operations. They are two examples of sequence data type (see sequence types - list, python tuple, range). Since Python is an evolving language, other sequence data types can be added. There is also another standard sequence data type: tuple.

Python Tuples and Sequences

For example, a python tuple contains several comma-separated values:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # python Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # python Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])
The output topless will always be in parenthesis so that the nested topless can be interpreted correctly. They can input with or without surrounding brackets, although often brackets are necessary anyhow (if the tuple is part of a larger expression). It is not possible to assign individual items of the tuple, however, it is possible to create python tuples that contain mutated objects in the form of a list.

Although python tuples may seem similar to lists, they are often used in different situations and for different purposes. python Tuples are immutable, and usually, have an asymmetrical sequence of elements that are accessed by unpacking (see later in this section) or sequencing (or by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by more iterations than the list.


A particular problem is the creation of tuples containing 0 or 1 items: the syntax has some additional quirks to accommodate these. Empty tuples will be made with empty brackets. A tuple with an item is created by following a value with a comma (it is not enough to enclose a value in parentheses). Ugly, but effective. for example:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

The statement t = 12345, 54321, 'Hello!' An example of tuple packing is value 12345, 54321 and 'Hello!' Are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t

This is, appropriately enough, called sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables to the left of the equal sign as there are items in the sequence. Note that many assignments are actually a combination of tuple packing and sequence unpacking.
Python Tuples and Sequences Python Tuples and Sequences Reviewed by Sk Jha on October 14, 2019 Rating: 5

No comments:

Powered by Blogger.