Tuples
Tuples
Tuples are very similar to lists in that they are ordered collections of items. However, there are some key differences between the two data types.
Concept: Tuples
Tuples are an ordered and immutable collection of items. Because tuples are immutable, they cannot be modified after they are created. This means that you cannot add, remove, or change items in a tuple.
Tuples are created with parentheses () instead of brackets.
ftp_socket = ('ftp', '192.168.1.65', '21')
ftp_uri = f"ftp://{ftp_socket[1]}:{ftp_socket[2]}"Working with tuples
As seen above, elements in a tuple can be accessed using their index, just like lists. However, because tuples are immutable, you cannot modify their contents.
Concept: Tuple methods & operators
A tuple can be used with all methods for lists, except for those that modify the contents of a list.
len(): Returns the number of items in the tuple.ftp_socket = ('ftp', '192.168.1.65', '21') print(len(ftp_socket)) # Output: 3join(): Joins the elements of a tuple into a string, using a specified separator.ftp_socket = ('ftp', '192.168.1.65', '21') print(' '.join(ftp_socket)) # Output: ftp 192.168.1.65 21count(): Returns the number of occurrences of a specified item in the tuple.users = ('Alice', 'Bob', 'Eve', 'Alice') print(users.count('Alice')) # Output: 2
All operators that work with lists also work with tuples.
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Concatenation | ('a', 'b') + ('c', 'd') | ('a', 'b', 'c', 'd') |
* | Repetition | ('a', 'b') * 2 | ('a', 'b', 'a', 'b') |
< | Less than | ('a', 'b') < ('c', 'd') | True |
> | Greater than | ('a', 'b') > ('c', 'd') | False |
== | Equal to | ('a', 'b') == ('a', 'b') | True |
!= | Not equal to | ('a', 'b') != ('c', 'd') | True |
in | Membership | 'a' in ('a', 'b') | True |
not in | Not membership | 'c' not in ('a', 'b') | True |
Tuples vs Lists
| Lists | Tuples | |
|---|---|---|
| When to use | The contents will change: a queue of servers to process, users you are collecting, results you are appending to. | The contents are one fixed record: a socket, a coordinate, a row from a file. Immutability is documentation. |