Tuple Data Types of Python Full Stack Road Series

Keywords: Python Attribute Programming Web Development

The only difference between tuples and lists is that lists can be changed, tuples can't be changed, and other functions are the same as lists.

Two ways to create tuples

First kind

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

Second kinds

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

If there is only one element in the meta-ancestor, a comma is needed, otherwise it becomes a string.

What can I learn from my learning process?
python Learning Exchange Button qun,784758214
//There are good learning video tutorials, development tools and e-books in the group.
//Share with you python enterprise talent demand and how to learn python from zero basis, and learn what content.
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

The method of tuple

View the number of occurrences of elements in the list

count(self, value):

attribute describe
value Element value
>>> ages = tuple((11, 22, 33, 44, 55))
>>> ages
(11, 22, 33, 44, 55)
>>> ages.count(11)
1

Find the location of elements in tuples

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

attribute describe
value Element value
start Starting position
stop End position
>>> ages = tuple((11, 22, 33, 44, 55))
>>> ages.index(11)
0
>>> ages.index(44)
3

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

Elements of tuples are immutable, but elements of elements of tuples may be immutable.

>>> 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 a tuple itself is immutable, but it can be modified if the element of a tuple is a list or dictionary.

Slices modify immutable types in situ

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

If you are still confused in the world of programming, you can join our Python learning button qun: 784758214 to see how our predecessors learned! Exchange experience! I am a senior Python development engineer, from basic Python scripts to web development, crawler, django, data mining, etc. To every little friend of Python! Share some learning methods and small details that need attention. Click to join us. python learner gathering place

Posted by canobi on Thu, 03 Oct 2019 13:47:13 -0700