Python tuples operate on instance resolution

  • 2020-04-02 14:07:54
  • OfStack

This article illustrates the python tuple operation method as an example and shares it with you for your reference. Specific analysis is as follows:

Generally speaking, python's function usage is quite flexible, and c, PHP usage is not quite the same, and js is quite similar.

In doing so, one of the most amazing things happens:


>>> t = (1, 3, 'b')
>>> q = t + ((3, 'abc'))
>>> q
(1, 3, 'b', 3, 'abc')

I was expecting (1, 3, 'b', (3, 'ABC ')), but it turned out to be (1, 3, 'b', 3,' ABC '), and at first I assumed that python was taking all the elements out and regrouping them in their original order. Then I tried again:


>>> q = t + ((3, 'abc'), '3')
>>> q
(1, 3, 'b', (3, 'abc'), '3')

So why did q = t + ((3, 'ABC ')) split the tuple? I tried again:


>>> q = t + ((3, 'abc', ('a')))
>>> q
(1, 3, 'b', 3, 'abc', 'a')

Python also removed the (' a ') from the tuple in the element (), and to test my idea, I tested it further:


>>> q = t + ((3, 'abc', ('a', 'ab')))
>>> q
(1, 3, 'b', 3, 'abc', ('a', 'ab'))

The result seems clear enough: when you do a + operation on a tuple, python automatically parses the added tuple, parses it into the simplest tuple and adds it up while maintaining the original tuple structure, i.e., unbracketed the multituples with only a single element.
So, what if I don't want python to remove () from the + operation?


>>> q = t + ((3, 'abc'),)
>>> q
(1, 3, 'b', (3, 'abc'))

I hope that this article has helped you to learn Python programming.


Related articles: