DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1

because you don’t have to create a new object every time
you need to store different values. When you have a value
that is constant and referenced in multiple parts of a
program, an immutable data type (such as a tuple), is
more memory efficient and easier to debug. You don’t
want some other part of your program to make changes
to a crucial piece of data stored in a mutable data type.


To create a tuple, you use parentheses instead of
brackets. You can use the type() function to identify a
Python data type you have created. Here is an example:


Click here to view code image


>>> person = (2012, 'Mike', 'CCNA')
>>> person
(2012, 'Mike', 'CCNA')
>>> type(person)
<class 'tuple'>

You access data in a tuple the same way as in a list—by
using brackets and the index value of the item in the
tuple that you want to return:


>>> person[0]
2012

What you can’t do with a tuple is make an assignment to
one of the values:


Click here to view code image


>>> person[0]=15
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item
assignment
Free download pdf