Python Tuples and sequences
Python Tuples and Sequences |
For example, a python tuple contains several comma-separated values:
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:
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:
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
Reviewed by Sk Jha
on
October 14, 2019
Rating:
No comments: