Tuples and Lists Type Conversions (Python)
Why would you convert lists to
tuples?
Let’s say you have such data which you never want to change,
then you should use tuple. (tuples == immutable).
They work like the array object in JavaScript. You can add
items, delete items from a list; but you cannot do that to a tuple, tuples have
a fixed size.
Why would you convert tuples to
lists?
Let’s say you want to make changes to the initial tuple
created, even though you know you can't modify the data directly. Therefore,
you can convert them to lists and then make the change, then convert them back
to tuples. (list == mutable).
Examples bellow shows conversion between tuple and list and
vice versa.
Here is an example demonstrating the mutable nature of lists in Python:
An example showing the immutable nature of tuples in Python:
An example of converting between tuples and lists to edit data:
Tip:
When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. For example, if current memory assignment is 140 bytes, when you want to append the 140th byte, maybe another 140 bytes will be assigned, making total of 280 bytes.
However, if you know you never want to edit the data, then you should use tuples. Tuples assigns exact size of the memory needed, and hence saves memory, especially when you use large blocks of memory.
If the tuple contains a list or a dictionary inside it, those can be changed. For example, Here is a tuple with list and dictionary inside:
Comments
Post a Comment