SoFunction
Updated on 2024-11-10

Python Getting Started Tutorial 4. Basic Tuple Operations Original

The previous section briefly describes theBasic Python List OperationsHere's another brief account of Python tuple-related operations

>>> dir(tuple) # View tuple properties and methods
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
>>> t1 = () # Create empty tuples
>>> tuple() # Create empty tuples
()
>>> (1,) # Create a tuple with only one element (create a tuple with only one element, with a comma after the element,)
(1,)
>>> 1,
(1,)
>>> 2,3 # Create a tuple by directly separating two values with a comma
(2, 3)
>>> x,y = 2,3 # The right side is a tuple
>>> x
2
>>> y
3
>>> x,y = y,x # Use tuple replication to realize that x and y exchange values
>>> x
3
>>> y
2
>>> t2 = (1,2,3)
>>> t2[1] # Get the tuple with the number 1
2
>>> t2[1] = 4 The # tuple can't change its value, an error will be reported here!
Traceback (most recent call last):
 File "<pyshell#14>", line 1, in <module>
  t2[1] = 4
TypeError: 'tuple' object does not support item assignment
>>> t3 = (2,3,3,3,4,5)
>>> (3) # count() method counts the number of elements 3 in the tuple
3
>>> (4) # index() method to get the positional number of element 4
4

Again, note that tuples can't change their values!

A simple tutorial to get you started.

Basically, it's easy to understand at a glance~O(∩_∩)O~

Unfinished business~~Welcome the discussion!