- Python Essentials
- Steven F. Lott
- 302字
- 2021-07-16 13:53:09
Using the tuple collection
The tuple
is one of the simplest collections available in Python. It is one of the many kinds of Python sequences. A tuple has a fixed number of items. For example, we might work with (x, y) coordinates or (r, g, b) colors. In these cases, the number of elements in each tuple is fixed by the problem domain. We don't want the flexibility of a collection that can vary in length.
Generally, we'll include ()
around a tuple
to set it apart from the surrounding syntax. This isn't always required; Python creates tuple
objects implicitly in some common contexts. However, it is always a good idea. If we write an assignment statement like this:
a = 2, 3
This statement will implicitly create a 2-tuple, (2, 3)
, and assign the object to the variable a
.
The tuple
class is part of Python's family of Sequence
classes; we can extract the items of a tuple
using their positional indices. The str
and byte
classes are also examples of Sequence. In addition to simple index values, we can use slice notation to pick items from a tuple
.
The value ()
is a zero-length tuple. To create a singleton tuple, we must use ()
and include a ,
character: this means that (12,)
is a singleton tuple. If we omit the ,
character we've written an expression, not a singleton tuple.
A trailing comma is required for a singleton tuple. An extra comma at the end of a tuple is quietly ignored everywhere else: (1, 1, 2)
is equal to (1, 1, 2,)
.
The tuple
class offers only two method functions: count()
and index()
. We can count the number of occurrences of a given item in a tuple
, and we can locate the position of an item in a tuple
.
- Learning Scala Programming
- Python科學計算(第2版)
- Effective Python Penetration Testing
- Java 9模塊化開發:核心原則與實踐
- SQL Server 2016數據庫應用與開發
- Mastering ROS for Robotics Programming
- C專家編程
- 深入理解BootLoader
- Python計算機視覺和自然語言處理
- Python Deep Learning
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- Java Web開發基礎與案例教程
- Java EE基礎實用教程
- HTML5 Game Development by Example:Beginner's Guide(Second Edition)
- 深入理解Zabbix監控系統