Storing Data Using Tuples

Lists aren’t the only kind of ordered sequence in Python. You’ve already learned about one of the others: strings (see Chapter 4, Working with Text). Formally, a string is an immutable sequence of characters. The characters in a string are ordered and a string can be indexed and sliced like a list to create new strings:

 >>>​​ ​​rock​​ ​​=​​ ​​'anthracite'
 >>>​​ ​​rock[9]
 'e'
 >>>​​ ​​rock[0:3]
 'ant'
 >>>​​ ​​rock[-5:]
 'acite'
 >>>​​ ​​for​​ ​​character​​ ​​in​​ ​​rock[:5]:
 ...​​ ​​print(character)
 ...
 
 a
 n
 t
 h
 r

Python also has an immutable sequence type called a tuple. Tuples are written using parentheses instead of brackets; like strings and lists, they can be subscripted, sliced, and ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.