How to declare a data method that contains only one element in Python

Source: Internet
Author: User
This article mainly introduces how to declare a single element in Python to contain tuples. This article is a summary of practical experience. If this problem is not met, it may not be noticed, if you need a friend, you can see this loss when debugging the program. I don't know why Python uses parentheses to declare the boundary. It is estimated that no suitable symbol can be found. Brackets are used to declare the list, curly brackets are used to declare the dictionary, and the element number can only be declared using brackets. Friends who have programming experiences in other languages know that brackets represent priority in other languages, and Python can also be used to indicate priority, which leads to the following idiotic problems.

The Code is as follows:


# Encoding = UTF-8

Obj = ('tuple ')

Print obj
Print type (obj)
Print len (obj)


Execution result

The Code is as follows:


Tuple

5


I originally wanted to declare a tuples with only one element, while Python probably thought that you only declare a string, so the result is converted into a tuples using the obj variable. This error is very invisible and cannot be debugged.
Solution: Add a comma at the end.

The Code is as follows:


# Encoding = UTF-8

Obj = ('tuple ',)

Print obj
Print type (obj)
Print len (obj)


Execution result

The Code is as follows:


('Tuple ',)

1


Use the tuple Keyword: unexpected results will be returned.

The Code is as follows:


# Encoding = UTF-8

Obj = tuple ('tuple ')

Print obj
Print type (obj)
Print len (obj)


Execution result

The Code is as follows:


('T', 'U', 'P', 'l', 'E ')

5

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.