are one of the core object types in . Although tuples may seem like lists, they are often used in different situations and for different purposes and unlike lists they are immutable.

Syntactically they are enclosed in parenthesis (or without them) instead of square brackets like lists, but they support arbitrary types and the usual operations available with lists.

>>> tuple = (123, 'Hello !', 21.03, 'AAA')
>>> tuple
(123, 'Hello World!', 21.03, 'AAA')
>>> len(tuple)
>>> tuple + ('BBB', 'CCC')
(123, 'Hello World!', 21.03, 'AAA', 'BBB', 'CCC')
>>> tuple
(123, 'Hello World!', 21.03, 'AAA')
>>> tuple[0]
>>> tuple[1]
'Hello World!'
>>> tuple[0] = 
Traceback (most recent call last):
   "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

If you look at the last line above you can see that changing of a tuple value is not permitted as tuples are immutable. That is the main difference between tuples and lists in Python.

The reason to use tuples is to provide a integrity in large programs where you want to make sure that some structures are not changed accidentally in the program. If you want to design a structure and do not want to accidentally change the original , tuples are what you should use.

Source link
thanks you RSS link


Please enter your comment!
Please enter your name here