Python Language Tuple: Difference between revisions
Line 32: | Line 32: | ||
=Exchanging Variable Values= | =Exchanging Variable Values= | ||
Tuples can be used to exchange to variable values without using a third temporary variable. | Tuples can be used to exchange to variable values without using a third temporary variable. | ||
<syntaxhighlight lang='python'> | |||
v1 = 'A' | |||
v2 = 'B' | |||
v1, v2 = v2, v1 | |||
print(v1) # will print B | |||
print(v2) # will print A | |||
</syntaxhighlight> | |||
=Named Tuples= | =Named Tuples= | ||
Named tuples can be a simple alternative to objects. | Named tuples can be a simple alternative to objects. |
Revision as of 05:13, 20 January 2022
Internal
Overview
A tuple is a immutable sequence type that contains zero or more elements and whose elements can be of different types. Once a tuple is defined, you can't add, delete or change items. A tuple is similar to a constant list, and could be used instead of a list, if we can afford the "list" to be immutable. Naturally, the list's mutating functions append()
, insert()
do not exist on tuples. There are several advantages of using a tuple instead of a list: a tuple uses less space than a list and they cannot be mutated by mistake. Positional function arguments can be grouped together and provided as a tuple in the function body (*args
).
Declaration
A tuple is declared by specifying commas after each of its elements, with the exception of the empty tuple, that uses ()
:
empty_tuple = ()
one_element_tuple = 1, # the trailing comma is mandatory
two_element_tuple = 1,2, # for two or more elements, the trailing comma is optional
For aesthetic reasons, and also to make the tuple more visible, the comma-driven declaration can be enclosed in optional parentheses:
empty_tuple = ()
one_element_tuple = (1,) # the trailing comma is mandatory
two_element_tuple = (1,2,) # for two or more elements, the trailing comma is optional
Conversion from other Data Structures
Tuple Unpacking
Assigning multiple variable at once is called "tuple unpacking":
t = (1, 'B', 3.0)
a, b, c = t
print(a) # will print 1
print(b) # will print 'B'
print(c) # will print 3.0
Exchanging Variable Values
Tuples can be used to exchange to variable values without using a third temporary variable.
v1 = 'A'
v2 = 'B'
v1, v2 = v2, v1
print(v1) # will print B
print(v2) # will print A
Named Tuples
Named tuples can be a simple alternative to objects.