Home  >  Article  >  Backend Development  >  Python Full Stack Road Series Tuple Data Type

Python Full Stack Road Series Tuple Data Type

高洛峰
高洛峰Original
2017-02-16 11:35:101178browse

The only difference between a tuple and a list is that the list can be changed, but the tuple cannot be changed. Other functions are the same as the list

Two ways to create a tuple

One

ages = (11, 22, 33, 44, 55)

The second

ages = tuple((11, 22, 33, 44, 55))

If there is only one element in the ancestor, then a comma needs to be added, otherwise it will become a string.

In [1]: t = (1)

In [2]: t
Out[2]: 1

In [3]: type(t)
Out[3]: int

In [4]: t = (1,)

In [5]: t
Out[5]: (1,)

In [6]: type(t)
Out[6]: tuple

Methods possessed by tuples

View the number of occurrences of elements in the list

count(self, value):

Attribute Description
value The value of the element
>>> ages = tuple((11, 22, 33, 44, 55))
>>> ages
(11, 22, 33, 44, 55)
>>> ages.count(11)
1

Find the position of the element in the tuple

index(self, value, start=None, stop=None):

##valueThe value of the elementstartStarting positionstopEnding position
>>> ages = tuple((11, 22, 33, 44, 55))
>>> ages.index(11)
0
>>> ages.index(44)
3
Attribute Description
List nesting

>>> T = (1,2,3,4,5)
>>> (x * 2 for x in T)
<generator object <genexpr> at 0x102a3e360>
>>> T1 = (x * 2 for x in T)
>>> T1
<generator object <genexpr> at 0x102a3e410>
>>> for t in T1: print(t)
... 
2
4
6
8
10
Tuple nesting modification

The elements of the tuple are unchangeable, but the elements of the tuple elements may be changeable The

>>> tup=("tup",["list",{"name":"ansheng"}])
>>> tup
('tup', ['list', {'name': 'ansheng'}])
>>> tup[1]
['list', {'name': 'ansheng'}]
>>> tup[1].append("list_a")
>>> tup[1]
['list', {'name': 'ansheng'}, 'list_a']
The element of the tuple itself cannot be modified, but if the element of the tuple is a list or dictionary, it can be modified

Slices modify immutable types in place

>>> T = (1,2,3)
>>> T = T[:2] + (4,)
>>> T
(1, 2, 4)

For more related articles on the Tuple Data Type of the Python Full Stack Road Series, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn