12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 12Tuples12.1 Tuples areimmutableA tuple is a sequence of values. The values can be any type, and they are indexed by integers, so inthat respect tuples arealotlikelists. The important difference isthat tuples are immutable.Syntactically, atuple isacomma-separated listofvalues:>>> t = 'a', 'b', 'c', 'd', 'e'Although itisnot necessary, itiscommon toenclose tuples inparentheses:>>> t = ('a', 'b', 'c', 'd', 'e')To create atuple withasingleelement, you have toinclude afinal comma:>>> t1 = 'a',>>> type(t1)A value inparentheses isnot atuple:>>> t2 = ('a')>>> type(t2)Another way to create a tuple is the built-in function tuple. With no argument, it creates an emptytuple:>>> t = tuple()>>> print t()If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of thesequence:>>> t = tuple('lupins')>>> print t('l', 'u', 'p', 'i', 'n', 's')

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

Saved successfully!

Ooh no, something went wrong!