Python has two very similar collection data types, list and tuple. The common definition is array.
tuple is defined by parentheses (). After definition, element content cannot be edited (that is, immutable). list is defined by brackets []. Its element content can be edited (that is, changeable). Editing actions include deleting pop(), appending append(), inserting insert()
Variable list
>>> name=['cong','rick','long'] >>> name[-2] #Equivalent to name[1] 'rick' >>> name.append('tony') >>> name.insert(0,'bob') #Insert bob at first position, index 0 >>> name.insert(2,'Jam') >>> name ['bob', 'cong', 'Jam', 'rick', 'long', 'tony'] >>> name.pop() #Delete last element 'tony' >>> name.pop(0) #Delete first element 'bob' >>> name ['cong', 'Jam', 'rick', 'long']
Immutable tuple
>>> month=('Jan','Feb','Mar') >>> len(month) 3 >>> month ('Jan', 'Feb', 'Mar') >>> month[0] 'Jan' >>> month[-1] 'Mar' >>> month.appnd('Apr') #Error will be reported when editing element content Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'appnd'
To edit an element defined by a tuple, first convert it to a list and then edit it:
>>> month_1=list(month) #Convert to list >>> month_1 ['Jan', 'Feb', 'Mar'] >>> month_1.append('Apr') #Appended >>> month_1 ['Jan', 'Feb', 'Mar', 'Apr'] >>> month ('Jan', 'Feb', 'Mar') >>> month=tuple(month_1) #Turn back to tuple >>> month ('Jan', 'Feb', 'Mar', 'Apr')
Make a "variable" tuple
>>> A= ('a', 'b', ['C', 'D']) >>> A[2] ['C', 'D'] >>> len(A) 3 >>> A[2][0] 'C' >>> A[2][0]='GG' >>> A[2][0]='MM' >>> A ('a', 'b', ['MM', 'D']) >>> A[2][0]='GG' >>> A[2][1]='MM' >>> A ('a', 'b', ['GG', 'MM']) >>> print(A[1]) #print() can be omitted b >>> A[2][0] GG