Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 7, 2022 06:16 pm GMT

List vs Tuple - When To Use Each?

In Python, lists and tuples are two built-in data types. Conceptually they are very similar, but there is some difference.

First, the lists are mutable. This means that once you have defined a list, you can modify it.

For example,

>>> l = ['a', 'b', 'c']>>> l[1] = 'x'>>> print(l)['a', 'x', 'c']

You can modify the list without any problems.

On the contrary, tuples are immutable. After creating a tuple, you cannot modify it. If you try to modify a tuple you will get an error, as shown in the following example:

l = ('a', 'b', 'c')l[1] = 'x'Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment

Tuples have an advantage over lists. They are more memory efficient and time efficient than the lists. This means that using a tuple to store a set of items will require less memory than using a list to store the same set of items. Also, creating a tuple requires less time than creating a list.

The following table summarizes the differences:

ListsTuples
Defined using square bracketsDefined using rounded brackets
Lists are mutable Tuples are immutable
Use more memory Use less memory
Slower Faster

Conclusions

Tuples are more memory and time efficient but cannot be modified.

Therefore, if you have data that don't need to be changed, you should use tuples. Instead, if you need to change data you are forced to use lists.


Original Link: https://dev.to/cscarpitta/list-vs-tuple-when-to-use-each-4e99

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To