Python basics: 1. Data type (tuple)

Source: Internet
Author: User

Hint: Python version is 2.7,windows system

1. Tuples (tuple)

Tuple, similar to list, but once initialized, a tuple cannot be modified without adding, deleting, or modifying elements.

1>>> colors = ('Red','Orange','Yello')2>>>Colors3('Red','Orange','Yello')4>>>type (colors)5<type'tuple'>

Empty tuple

1 >>> color = ()2 >>> color3 ()

1 elements

1 >>> color = (1)      #这is the same as a mathematical parenthesis, so when there is only one element, add a comma at the end of the 2 >>> Color 3 14 >>> color = (1,)     #是这种 5 >>> color 6 (1,)

Modify elements, cannot be modified, and does not add or remove methods

1>>> colors[0] =' White'2 3 Traceback (most recent):4File"<pyshell#18>", line1,inch<module>5colors[0] =' White'6TypeError:'tuple' ObjectDoes not support item assignment

Other similar to list

1>>>Colors[0]2 'Red'3>>> colors[-1]4 'Yello'5>>> colors[0:1]6('Red',)7>>> colors[-1:-2]8 ()9>>> colors[-1:]Ten('Yello',) One>>> colors[-1:1] A () ->>> colors[-1:-1] - () the>>> colors[-2:-1] -('Orange',) ->>> colors[-3:-2] -('Red',)

When there is a list in a tuple

1>>> test = ('a','b','C', ['D','e','F'])2>>> test[3]3['D','e','F']4>>> Type (test[3])5<type'List'>6>>> test[3] = ['D']#You cannot modify the list7 8 Traceback (most recent):9File"<pyshell#38>", Line 1,inch<module>TenTEST[3] = ['D'] OneTypeError:'tuple'Object does notSupport Item Assignment A  - #You can modify the elements of a list ->>> Test[3][0] ='g' the>>> Test[3][1] ='h' ->>> test[3][2] ='I' ->>>Test -('a','b','C', ['g','h','I']) + #Delete List element ->>> test[3].pop () + 'I' A>>>Test at('a','b','C', ['g','h'])

In fact, the non-modification of the tuple refers to each element of the point of the address is unchanged, pointing to ' red ' cannot be changed to point to ' white ', when pointing to the list, the list can not be changed to other elements, but the list of elements may change

Python basics: 1. Data type (tuple)

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.