Skip to Content
The Python Book
book

The Python Book

by Rob Mastrodomenico
January 2022
Beginner to intermediate
272 pages
6h 51m
English
Wiley
Content preview from The Python Book

8Tuples

The good thing about covering lists is that it then makes tuples much easier to cover. Tuples are essentially lists. You access them in exactly the same way and many things we covered in lists are relevant to tuples, the big difference is tuples can't be modified. Why would you want something that cannot be modified? Well its actually more useful than you would think, it prevents you from accidentally changing something that you may rely on in your code.

Let's take the numbers list we defined at the start of the list section:

image

We can rewrite this as a tuple as follows:

image

Looks very similar doesn't it! Now let's try and access the first element of the tuple, again we do it in the same way as we would do in a list

image

And to get the last number we would do

image

We can splice the tuple just like we would a list, so if we wanted everything except the last two values then we do it in exactly the same way we would do in a list

image

So what is the point in tuples? Well let's try and change ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

The Quick Python Book, Third Edition

The Quick Python Book, Third Edition

Naomi Ceder, David Fugate
Serious Python

Serious Python

Julien Danjou

Publisher Resources

ISBN: 9781119573319Purchase Link