Tuples can be used as immutable lists from "summary" of Fluent Python by Luciano Ramalho
Tuples can be used as immutable lists. Although a tuple is not as flexible as a list, it is faster, and its immutable nature can provide some advantages. A tuple is an immutable, fixed-size, and heterogeneous sequence, just like a list. One common tuple use is as a record with no field names. Since tuples are immutable, their elements are like records fields. For example, a query function can return a tuple with the query string and a tuple of parameters.
Tuples support all the list methods that do not involve adding or removing items, such as slicing and indexing. The + operator can be used to concatenate tuples to form a new tuple.
If a tuple holds references to objects, those references will not change, but the objects themselves can be modified if they are mutable. However, if the referenced items are immutable, then the tuple is effectively immutable too.
To build up a tuple from other iterables, the tuple constructor accepts any iterable as an argument. This can be useful when converting a list to a tuple. For instance, when receiving a variable-length argument list in a function, you may want to convert it to a tuple to ensure it remains immutable.
Tuples can also be used as keys in dictionaries, as long as they contain only immutable elements themselves. This is because a tuple's hash value is computed from the hash values of the items it contains.
In summary, tuples can be used as immutable lists for scenarios where immutability is desired or advantageous. They provide a simple and efficient way to represent fixed collections of items, especially when those items should not be changed.
Read More
Continue reading the Microbook on the Oter App. You can also listen to the highlights by choosing micro or macro audio option on the app. Download now to keep learning!
Now you can listen to your microbooks on-the-go. Download the Oter App on your mobile device and continue making progress towards your goals, no matter where you are.