官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 五寨县| 德令哈市| 辉南县| 当阳市| 日照市| 凤凰县| 道孚县| 稻城县| 康平县| 普格县| 巩义市| 淮滨县| 赤峰市| 五峰| 韩城市| 陆河县| 南皮县| 阳西县| 福贡县| 灵石县| 安阳县| 花莲县| 甘南县| 云梦县| 兴安县| 德令哈市| 新营市| 安国市| 武清区| 延津县| 南川市| 佛山市| 岑溪市| 秦皇岛市| 华阴市| 鄂伦春自治旗| 铁岭县| 太保市| 衡阳市| 津南区| 福贡县|