Tuples belong to immutable sequences , Elements in tuples cannot be modified . So tuples don't add elements 、 Modifying elements 、 Delete element related methods .
Tuple support such as Lower operation :
1. Index access
2. Slicing operation
3. Connection operation
4. Membership operations
5. Comparison operation
6. Count : Tuple length len()、 Maximum max()、 minimum value min()、 Sum up sum() etc. .
Tuple creation :
1. adopt () Creating a tuple . Parentheses can be omitted .
a = (10,20,30) perhaps a = 10,20,30
Be careful : If the tuple has only one element , Must be followed by a comma . This is because the interpreter will put (1) Interpreted as an integer 1, and (1,) Will be interpreted as tuples .
>>> a = (1)
>>> type(a)
<class 'int'>
>>> a = (1,) # perhaps a = 1,
>>> type(a)
<class 'tuple'>
2. adopt tuple() Creating a tuple :
>>> tuple("abc")
('a', 'b', 'c')
>>> tuple(range(3))
(1, 2, 3)
>>> tuple([2,3,4])
(2, 3, 4)
Compare :
tuple() Can receive list 、 character string 、 Other sequence types 、 Generation of iterators, etc Tuples .
list() Can receive tuples 、 character string 、 Other sequence types 、 Generation of iterators, etc list .
Element access of tuples :
The element access of tuples is the same as that of lists , It just returns the tuple object .
>>> a = (20,10,30,9,8)
>>> a[1]
10
>>> a[1:3]
(10, 30)
>>> a[:4]
(20, 10,30, 9)
Sorting tuples , Only built-in functions can be used sorted(tupleObj), And generate a new list object .
>>> a = (20,10,30,9,8)
>>> sorted(a)
[8, 9, 10, 20, 30]
zip pack :
zip( list 1, list 2,...) Will be multiple list The elements at the corresponding positions are combined into Tuples , And return this zip object .
>>> a = [10,20,30]
>>> b = [40,50,60]
>>> c = [70,80,90]
>>> d = zip(a,b,c)
>>> list(d)
[(10, 40, 70), (20, 50, 80), (30, 60, 90)]
The generator deduces to create tuples :
The generator derivation generates neither a list nor a tuple , It is A generator object . We can use the generator object , Into a list or tuple . You can also use the... Of the generator object __next__() Method , Or use it directly as an iterator object . No matter how you use it , After element access , If you need to revisit the elements , The generator object must be recreated .
>>> s = (x*2 for x in range(5))
>>> tuple(s)
(0,2,4,6,8)
>>> tuple(s)
()