Getting Started with Python (v) tuple

Source: Internet
Author: User

In the front there is an increase in tuples tuple is one of the sequence, the elements of a tuple are enclosed in parentheses ():

Tup1 = (1, ' Hello ', ' a ', ' B ', ' C ', 2.01) print (tup1) #使用for循环依次打印tuple中的每一个元素for v in Tup1:print (v) #使用下标访问每一个元素for I In range (len (tup1)): Print (Tup1[i]) >>>1helloabc2.01

The creation of a tuple is as simple as enclosing the element in parentheses () and separating the elements with commas.

A tuple can hold any type of element, except for integers, floating-point numbers, strings, or tuples, lists, and so on, in addition to the code shown above.

Tup2 = (tup1, ' tup2 ') #print (tup2) for V in Tup2:print (v) >>> (1, ' Hello ', ' a ', ' B ', ' C ', 2.01) tup2

The most important feature of the tuple is: after the creation, the element cannot be modified (including delete), the modification will be directly error.

TUP2[1] = ' abc ' Traceback (most recent): File "<pyshell#18>", line 1, <module> tup2[1] = ' abc ' TypeError: ' Tuple ' object does not support item assignment

The access of the tuple element, which has been shown by subscript to access, in fact, can also be intercepted, to get a sub-tuple

Print (tup1[1:]) >>> (' Hello ', ' a ', ' B ', ' C ', 2.01) print (Tup1[1:-1:2]) >>> (' Hello ', ' B ')

Tuple connection, two tuple can be "+", the two tuple is connected to a new tuple

tup3= (' abc ',) #定义只有一个元素的tuple, need to be added in the back ', ' Print (Tup1 + tup3) >>> (1, ' Hello ', ' a ', ' B ', ' C ', 2.01, ' abc ')

Gets the number of tuple elements:

Print (len (tup1))

To convert a list to a tuple:

List1 = [' A ', ' B ', ' C ']tuple (list1) >>> (' A ', ' B ', ' C ')


Getting Started with Python (v) 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.