- Python Data Structures and Algorithms
- Benjamin Baka
- 250字
- 2021-07-09 19:45:02
Tuples
Tuples are immutable sequences of arbitrary objects. They are indexed by integers greater than zero. Tuples are hashable, which means we can sort lists of them and they can be used as keys to dictionaries. Syntactically, tuples are just a comma-separated sequence of values; however, it is common practice to enclose them in parentheses:
tpl= ('a', 'b', 'c')
It is important to remember to use a trailing comma when creating a tuple with one element, for example:
t = ('a',)
Without the trailing comma, this would be interpreted as a string.
We can also create a tuple using the built-in function tuple(). With no argument, this creates an empty tuple. If the argument to tuple() is a sequence then this creates a tuple of elements of that sequence, for example:

Most operators, such as those for slicing and indexing, work as they do on lists. However, because tuples are immutable, trying to modify an element of a tuple will give you a TypeError. We can compare tuples in the same way that we compare other sequences, using the ==, > and < operators.
An important use of tuples is to allow us to assign more than one variable at a time by placing a tuple on the left-hand side of an assignment, for example:

We can actually use this multiple assignment to swap values in a tuple, for example:

A ValueError will be thrown if the number of values on each side of the assignment are not the same.
- C++程序設計教程
- LabVIEW Graphical Programming Cookbook
- SQL學習指南(第3版)
- JavaScript Unlocked
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- CouchDB and PHP Web Development Beginner’s Guide
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Reactive Android Programming
- Flutter跨平臺開發入門與實戰
- Working with Odoo
- 打開Go語言之門:入門、實戰與進階
- Node學習指南(第2版)
- .NET 4.5 Parallel Extensions Cookbook
- 運維前線:一線運維專家的運維方法、技巧與實踐
- 青少年學Python(第2冊)