Python declares a tuple data method that contains only one element

  • 2020-04-02 14:01:08
  • OfStack

When debugging the program, I have suffered from this problem. I don't know why Python USES the parentheses to make the tuple declaration boundary character, and I guess I can't find the proper symbol. Brackets are used to declare lists, curly braces are used to declare dictionaries, and tuple Numbers can only be declared in brackets. Those of you who have programming experience in other languages know that parentheses are used to indicate priorities in other languages, and Python can be used to indicate priorities, which raises the following idiotic question.


# encoding=UTF-8
 
obj = ('tuple')
 
print obj
print type(obj)
print len(obj)

The execution result

tuple
<type 'str'>
5

I was going to declare a tuple with only one element, and Python figured out that you're just declaring a string so the obj variable becomes a tuple. This error is very invisible and difficult to debug.
Solution: add a comma at the end

# encoding=UTF-8
 
obj = ('tuple',)
 
print obj
print type(obj)
print len(obj)

The execution result

('tuple',)
<type 'tuple'>
1

Use the tuple keyword: you'll get unexpected results

# encoding=UTF-8
 
obj = tuple('tuple')
 
print obj
print type(obj)
print len(obj)

The execution result

('t', 'u', 'p', 'l', 'e')
<type 'tuple'>
5


Related articles: