Python tuple tuples

Source: Internet
Author: User

@ Original website

Because the tuple is immutable, the code is more secure. If possible, you can use a tuple instead of a list as much as possible.

The trap of a tuple: when you define a tuple, the elements of a tuple must be determined when defined, such as:

>>> t = (1, 2)>>> t(1, 2)

If you want to define an empty tuple, you can write () :

>>> t = ()>>> t()

However, to define a tuple with only 1 elements, if you define this:

>>> t = (1)>>> t1

The definition is not a tuple, it is 1 this number! This is because the parentheses () can represent both tuple and parentheses in the mathematical equation, which creates ambiguity, so Python rules that, in this case, the parentheses are calculated, and the result is naturally 1 .

Therefore, only 1 elements of a tuple definition must be added with a comma , to disambiguate:

>>> t = (1,)>>> t(1,)

Python will also add a comma when displaying a tuple of only 1 elements, , lest you misunderstand the parentheses in the mathematical sense.

Python tuple tuples

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.