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

Python Full Stack Road Series Tuple Data Type

高洛峰
Release: 2017-02-16 11:35:10
Original
1196 people have browsed it

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)
Copy after login

The second

ages = tuple((11, 22, 33, 44, 55))
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login
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
Copy after login
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']
Copy after login
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)
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template