Python learning notes (9) Python tuples and dictionaries (1)

Python tuple

Tuple is a Python object type, tuple is also a sequence

Tuples in Python are similar to lists, except that the elements of tuples cannot be modified

Tuples use parentheses, lists use square brackets

Tuples are created by adding elements in parentheses separated by commas

1 >>> a = 123,"aaa",["python","pass"]
2 >>> a
3 (123, 'aaa', ['python', 'pass'])
4 >>> type(a)
5 <type 'tuple'>
6 >>> print "I love %s,and I am a %s"%("Python","programmer")
7 I love Python,and I am a programmer

Tuple is a sequence. The basic operations of sequence are len(), +, *, in, max(), min(), cmp()

Transformation between tuples and sequences

Tuples are immutable

 1 >>> a =(1,2,3)
 2 >>> id(a)   #a and b tuples are two different objects
 3 44307080L
 4 >>> b=(1,3,2)
 5 >>> id(b)
 6 48683696L
 7 >>> a
 8 (1, 2, 3)
 9 >>> len(a) #Calculated length
10 3
11 >>> b
12 (1, 3, 2)
13 >>> a + b  #Join two tuples together
14 (1, 2, 3, 1, 3, 2)
15 >>> a * 3  #Repeat a tuple 3 times
16 (1, 2, 3, 1, 2, 3, 1, 2, 3)
17 >>> 3 in a  #Judge whether the element 3 is in the tuple a
18 True
19 >>> 4 in a  #Judge whether the element 4 is in the tuple a
20 False
21 >>> max(a)  #Calculate the maximum value in tuple a
22 3
23 >>> min(a)  #Calculating the minimum value in tuple a
24 1
25 >>> cmp(a,b) #Compare the size of tuples a and b
26 -1
27 >>> alst =list(a) #Convert tuples to lists
28 >>> alst
29 [1, 2, 3]
30 >>> c =tuple(alst) #Convert list to tuple
31 >>> c
32 (1, 2, 3)
33 >>> a
34 (1, 2, 3)
35 >>> a.append(4) #Append element to tuple, tuple cannot append element
36 Traceback (most recent call last):
37   File "<stdin>", line 1, in <module>
38 AttributeError: 'tuple' object has no attribute 'append' #Tuple has no attribute append
39 >>> dir(tuple) #dir view tuples, only count index
40 ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
41 >>> dir(list)
42 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Indexes and slices of tuples, similar to lists and strings

When a tuple contains only one element, you need to add a comma after the element

 1 >>> a
 2 (1, 2, 3)
 3 >>> a[0]  #Extract elements by index value
 4 1
 5 >>> a[1]
 6 2
 7 >>> a[2]
 8 3
 9 >>> a[1:] #Extract elements by slicing
10 (2, 3)
11 >>> a[0:2]
12 (1, 2)
13 >>> a[::-1] #Invert tuple a
14 (3, 2, 1)
15 >>> alst[1]=100  #Add the element alst[1] to the alst list
16 >>> alst
17 [1, 100, 3]
18 >>> a[1]=100  #Elements cannot be added in tuples in this way
19 Traceback (most recent call last):
20   File "<stdin>", line 1, in <module>
21 TypeError: 'tuple' object does not support item assignment  Tuple does not support modification
22 >>> temp =list(a)    #Convert tuple a to a list and store it in temp temporary variable
23 >>> temp[1]=100    #Add 100 to list temp index at 1
24 >>> a =tuple(temp)  #Then convert temp to tuple
25 >>> a          #Realize the mutual conversion between tuples and lists
26 (1, 100, 3)
27 >>> [1]      #The single [1] is a list
28 [1]
29 >>> type([1])
30 <type 'list'>
31 >>> type((1))   #Single (1) is an integer
32 <type 'int'>
33 >>> type((1,))  #A single (1,) is a tuple. When a tuple contains only one element, you need to add a comma after the element
34 <type 'tuple'>
35 >>>

count() and index() of tuples

 1 >>> a
 2 (1, 100, 3)
 3 >>> b=a*3
 4 >>> b
 5 (1, 100, 3, 1, 100, 3, 1, 100, 3)
 6 >>> b.count(1) #Count the number of occurrences of 1
 7 3
 8 >>> b.index(3) #Calculate the location of the first occurrence of 3
 9 2

The meaning of tuple

Tuple is faster than list operation

Write protect data because tuples are not modifiable

Can be used in string formatting

key as dictionary

Keywords: Python Attribute

Added by pixelsoul on Wed, 01 Apr 2020 11:34:35 +0300