Python Basic Learning Article Python tuple

Source: Internet
Author: User

Tuples are a data structure built into Python. Tuples consist of different elements, each of which can store different types of data, such as strings, numbers, or even tuples. Tuples are write-protected, that is, tuples cannot be modified after they are created, and tuples typically represent a single row of data, while elements in tuples represent different data items.

One, the creation of the tuple

A tuple (tuple) consists of a series of elements, all of which are enclosed in a pair of parentheses. When you create a tuple, you can not specify the number of elements, which is equivalent to an indeterminate array, but you cannot modify the length of the tuple once it is created .

The tuple creation format is as follows:

Tuple_name = (element 1, Element 2, ...) )

Example: initialization of a tuple

Tuple_name = ("Apple","banana","grape ","Orange")

Creating an empty tuple requires a pair of empty parentheses

Tuple_name= ()

There is only one element in the tuple

Tuple_name= ("Apple",)

Attention:

The index of a tuple is counted from 0, so Tuple[0] obtains the 1th element in a tuple of tuples.

Ii. access to the tuple

The value of the element in the tuple is accessed through the index. The tuple's access format is as follows:

Tuple_name[n]

When a tuple is created, the value of its inner element cannot be modified, and if an element in the tuple is modified, the runtime will error. Therefore, the tuple does not support assignment operations.

A negative index is counted from the end of the tuple, the trailing element index is represented as "1", and the element index at the secondary end is expressed as "2".

For example:

650) this.width=650; "title=" 1 "style=" border-left-0px; border-right-width:0px; Background-image:none; border-bottom-width:0px; Float:none; padding-top:0px; padding-left:0px; Margin-left:auto; Display:block; padding-right:0px; border-top-width:0px; Margin-right:auto "border=" 0 "alt=" 1 "src=" http://img1.51cto.com/attachment/201409/2/6459431_1409670631QCbt.jpg " Width= "507" height= "144"/>

TUPLE[-1] has a value of value4

TUPLE[-2] has a value of value3

a shard (slice) is a subset of tuples that are specified from the 1th index to the 2nd index (which does not contain the elements pointed to by the 2nd index).

The Shard index can be positive or negative, and the format of the Shard is as follows:

TUPLE_NAME[M:N]

For example:

650) this.width=650; "title=" 1[1] "style=" border-left-0px; border-right-width:0px; Background-image:none; border-bottom-width:0px; Float:none; padding-top:0px; padding-left:0px; Margin-left:auto; Display:block; padding-right:0px; border-top-width:0px; Margin-right:auto "border=" 0 "alt=" 1[1] "src=" http://img1.51cto.com/attachment/201409/2/6459431_ 1409670636fw8p.jpg "width=" 518 "height=" 139 "/>

Tuple_name[1:3] will return (VALUE2,VALUE3,VALUE4)

Example: demonstrating how negative indexes and shard indexes are used

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2.7#Author: [email protected] tuple= ("Apple","Banana","Grape","Orange")PrintTuple[-1]PrintTuple[-2]tuple2= Tuple[1:3]tuple3= Tuple[0:-2]tuple4= Tuple[2:-2]PrintTuple2PrintTuple3PrintTuple4

Output Result:

----------python2.7----------orangegrape ('banana'Grape ' ) ('apple'banana'-Normal termination

Tuples can also be made up of other tuples.

For example, a two-tuple can be represented as:

Tuple = (("T1","T2"), ("T3",  "T4"))

Example:

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2.7#Author: [email protected]Fruit1 = ("Apple","Banana") Fruit2= ("Grape","Orange") Tuple=(FRUIT1,FRUIT2)PrinttuplePrint "tuple[0][1] =", tuple[0][1]Print "tuple[1][1] =", tuple[1][1]Print "tuple[0][1] =", Tuple[1][2]

Output Result:

----------python2.7----------(('Apple','Banana'), ('Grape','Orange')) tuple[0][1] = Banana---represents the 2nd element that accesses a 1th tuple in a tuple tuple tuple[1][1] = Orange---represents the 2nd element that accesses a 2nd tuple in a tuple tuple tuple[0][1] =---represents the 3rd element that accesses the 2nd tuple in a tuple tuple because the element does not exist, the tuple's index access is out of bounds, and the following error message is returned. Traceback (most recent): File"noname1.py", Line 12,inch<module>Print "tuple[0][1] =", tuple[1][2]indexerror:tuple index out of range output completed (0 seconds elapsed)-Normal termination

The storage structure of the tuple tuples is as follows;

650) this.width=650; "title=" 1[2] "style=" border-left-0px; border-right-width:0px; Background-image:none; border-bottom-width:0px; Float:none; padding-top:0px; padding-left:0px; Margin-left:auto; Display:block; padding-right:0px; border-top-width:0px; Margin-right:auto "border=" 0 "alt=" 1[2] "src=" http://img1.51cto.com/attachment/201409/2/6459431_ 1409670638qcy3.jpg "width=" 535 "height=" 214 "/>

In Python, the process of creating tuples is called "packaging." Instead, tuples can perform "unpacking" operations. Unpacking can assign individual elements in tuples to multiple variables. This avoids the use of circular traversal methods to get the value of each element, reducing the complexity of the code and expressing it more naturally.

Example:

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2.7#Author: [email protected]#PackingTuple = ("Apple","Banana","Grape","Orange")#UnpackingA,b,c,d =tuplePrintA,b,c,d

Output Result:

----------python2.7-----------Normal termination

Three, meta-group traversal

A tuple's traversal refers to the value of each element in a tuple that is accessed sequentially through a looping statement . Traversing tuples requires the use of the range () and Len () functions. Description: Range () and Len () are all built-in functions of python that can be called directly and do not require an import statement to be imported into the module.

Len () calculates the number of elements in the tuple tuples , and range () returns a list of numbers.

The Declaration of Range () is as follows:

Range ([Start,]stop[,step])--List ofintegers description:1, Range () returns a list of numbers that are incremented or decremented, and the element value of the list is determined by 3 parameters 2  , the parameter start represents the starting value of the list, the default is 03, the parameter stop represents the value of the end of the list, the parameter is not missing 4, the parameter step represents the step, increment or decrement the value each time, the default value is 1

For example:

Range (5) returns a list of [0,1,2,3,4]

Example:

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2.7#Author: [email protected]#demonstrates traversal of a two meta- tupletuple= (("Apple","Banana"),("Grape","Orange"),("Watermelon",),("Grapefruit",)) forIinchRange (len (tuple)):Print "tuple[%d]"I"",     forJinchRange (len (tuple[i)):PrintTUPLE[I][J],"",    Print

Output Result:

----------python2.7----------tuple[0]  apple  banana tuple[1]  grape  Orange tuple[ 2]  watermelon tuple[3]  -Normal termination

You can also use map () to "unpack" a tuple tuple, get each child tuple, and then iterate through each of the sub-tuples, outputting the values of all the elements in the tuple tuple.

The Declaration of Map () is as follows:

Map (function,sequence[,sequence,...]) -andlist description:1, Map () returns a list of functions processed by a custom function, 2, parameter funtion is the function created, which is used to handle parameter sequence. If the function has a value of None, Map () returns a tuple or list consisting of the parameter sequence, 3, the parameter sequence represents the sequence, and the tuple and list are sequences.

Example:

#!/usr/bin/env python#-*-coding=utf-8-*-#Using GPL v2.7#Author: [email protected]#Demo map () implements the traversal of tuplestuple= (("Apple","Banana"),("Grape","Orange"),("Watermelon",),("Grapefruit",)) K=0 forAinchmap (none,tuple):Print "tuple[%d]"K"",     forXinchA:PrintX"",    Printk+ = 1

Output Result:

----------python2.7----------tuple[0]  apple  banana tuple[1]  grape  Orange tuple[ 2]  watermelon tuple[3]  -Normal termination

Python Basic Learning Article Python tuple

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.