06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9<br />

Tuples<br />

9.1 Mutability and tuples<br />

So far, you have seen two compound types: strings, which are made up of characters;<br />

and lists, which are made up of elements of any type. One of the differences<br />

we noted is that the elements of a list can be modified, but the characters in a<br />

string cannot. In other words, strings are immutable and lists are mutable.<br />

There is another type in <strong>Python</strong> called a tuple that is similar <strong>to</strong> a list except that<br />

it is immutable. Syntactically, a tuple is a comma-separated list of values:<br />

>>> tuple = ’a’, ’b’, ’c’, ’d’, ’e’<br />

Although it is not necessary, it is conventional <strong>to</strong> enclose tuples in parentheses:<br />

>>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’)<br />

To create a tuple <strong>with</strong> a single element, we have <strong>to</strong> include the final comma:<br />

>>> t1 = (’a’,)<br />

>>> type(t1)<br />

<br />

Without the comma, <strong>Python</strong> treats (’a’) as a string in parentheses:<br />

>>> t2 = (’a’)<br />

>>> type(t2)<br />

<br />

Syntax issues aside, the operations on tuples are the same as the operations on<br />

lists. The index opera<strong>to</strong>r selects an element from a tuple.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!