Python Language Tuple: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(18 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Internal=
=Internal=
* [[Python_Language#Tuple|Python Language]]
* [[Python_Language#Tuple|Python Language]]
=TODO=
<font color='darkkhaki'>
* TO PROCESS:  [[PyOOP]] "Tuples and named tuples", "Named tuples"
</font>
=Overview=
=Overview=
A tuple is a immutable [[Python_Language#Sequence_Types|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 [[Python Language List#Overview|list]], and could be used instead of a list, if we can afford the "list" to be immutable. Naturally, the list's mutating functions  <code>append()</code>, <code>insert()</code> 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 [[Python_Language_Functions#Gather_Positional_Arguments_with_.2A|grouped together and provided as a tuple]] in the function body (<code>*args</code>).
A tuple is a immutable [[Python_Language#Sequence_Types|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 [[Python Language List#Overview|list]], and could be used instead of a list, if we can afford the "list" to be immutable. Naturally, the list's mutating functions  <code>append()</code>, <code>insert()</code> 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 [[Python_Language_Functions#Gather_Positional_Arguments_with_.2A|grouped together and provided as a tuple]] in the function body (<code>*args</code>).
Line 18: Line 23:
</syntaxhighlight>
</syntaxhighlight>
=Access a Tuple=
=Access a Tuple=
To access the elements of a tuple, use the same bracket notation as for a list. The index is 0-based:
<syntaxhighlight lang='py'>
t = ('a', 'b', 'c')
assert 'a' == t[0]
</syntaxhighlight>


=Conversion from other Data Structures=
=<span id='Conversion_from_other_Data_Structures'></span>Conversion from other Data Structures with <tt>tuple()</tt>=
The <code>tuple()</code> converts lists to tuples:
The <code>tuple()</code> converts lists, or iterables, in general, to tuples:
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
l = ['a', 'b', 'c']
l = ['a', 'b', 'c']
t = tuple(l)
t = tuple(l)
print(t)
print(t)
assert 'a' == t[0]
assert 'b' == t[1]
assert 'c' == t[2]
</syntaxhighlight>
=Tuple Concatenation=
==Tuple Concatenation with <tt>+</tt>==
Tuples can be concatenate with the <code>+</code> operator:
<syntaxhighlight lang='python'>
t = (1, 2, 3) + (4, 5)
</syntaxhighlight>
==Tuple Concatenation with <tt>*</tt>==
Multiplying the tuple by an integer has the effect of concatenating that many copies of the tuple.
<syntaxhighlight lang='py'>
t = (1, 2) * 3 #  (1, 2, 1, 2, 1, 2)
</syntaxhighlight>
</syntaxhighlight>


Line 37: Line 61:
</syntaxhighlight>
</syntaxhighlight>


=Exchanging Variable Values=
A common use of variable unpacking is iterating over sequences of tuples of lists:
Tuples can be used to exchange to variable values without using a third temporary variable.
<syntaxhighlight lang='python'>
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
    printf(f'{a}, {b}, {c}')
</syntaxhighlight>
 
==Exchanging Variable Values==
Tuple unpacking can be used to swap to variable values without using a third temporary variable.
<syntaxhighlight lang='python'>
<syntaxhighlight lang='python'>
v1 = 'A'
v1 = 'A'
Line 46: Line 77:
print(v2)  # will print A
print(v2)  # will print A
</syntaxhighlight>
</syntaxhighlight>
=Plucking a Few Elements from the Beginning of a Tuple=
<syntaxhighlight lang='py'>
t = (1, 2, 3, 4, 5)
a, b, *rest = values # a is 1, b is 2 and rest is (3, 4, 5)
</syntaxhighlight>
If you want to discard the rest:
<syntaxhighlight lang='py'>
t = (1, 2, 3, 4, 5)
a, b, *_ = values
</syntaxhighlight>
=Slices=
The same rule as for lists apply: {{Internal|Slicing_Lists_and_Tuples_in_Python#Overview|Slicing Lists and Tuples in Python}}


=Named Tuples=
=Named Tuples=
Named tuples can be a simple alternative to objects.
Named tuples can be a simple alternative to objects.
=Tuple Methods=
==<tt>count(val)</tt>==
Counts the number of occurrences of the given value.

Latest revision as of 21:48, 16 May 2024

Internal

TODO

  • TO PROCESS: PyOOP "Tuples and named tuples", "Named tuples"

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

Access a Tuple

To access the elements of a tuple, use the same bracket notation as for a list. The index is 0-based:

t = ('a', 'b', 'c')
assert 'a' == t[0]

Conversion from other Data Structures with tuple()

The tuple() converts lists, or iterables, in general, to tuples:

l = ['a', 'b', 'c']
t = tuple(l)
print(t)
assert 'a' == t[0]
assert 'b' == t[1]
assert 'c' == t[2]

Tuple Concatenation

Tuple Concatenation with +

Tuples can be concatenate with the + operator:

t = (1, 2, 3) + (4, 5)

Tuple Concatenation with *

Multiplying the tuple by an integer has the effect of concatenating that many copies of the tuple.

t = (1, 2) * 3 #  (1, 2, 1, 2, 1, 2)

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

A common use of variable unpacking is iterating over sequences of tuples of lists:

seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
     printf(f'{a}, {b}, {c}')

Exchanging Variable Values

Tuple unpacking can be used to swap 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

Plucking a Few Elements from the Beginning of a Tuple

t = (1, 2, 3, 4, 5)
a, b, *rest = values # a is 1, b is 2 and rest is (3, 4, 5)

If you want to discard the rest:

t = (1, 2, 3, 4, 5)
a, b, *_ = values

Slices

The same rule as for lists apply:

Slicing Lists and Tuples in Python

Named Tuples

Named tuples can be a simple alternative to objects.

Tuple Methods

count(val)

Counts the number of occurrences of the given value.