The road to Python learning----Introduction to tuples

tuple

Tuples are similar to lists, except that the elements of a tuple cannot be modified.

The so-called immutability of a tuple means that the contents of the memory pointed to by the tuple are immutable

tuple creation

To create a tuple, simply add elements in parentheses and separate them with commas.

tup1 =  ( 'Google' ,  'Runoob' ,  1997 ,  2000 ) 
tup2 =  ( 1 ,  2 ,  3 ,  4 ,  5  ) 
tup3 =  "a" ,  "b" ,  "c" ,  "d"    # no need for parentheses too Can

print ( type ( tup3 ) )

>> > < class  'tuple' >
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Create empty tuple:

tup_empty =  ( )
  • 1

Create a tuple with only one element:

tup_one =  ( 2 , ) 
tup_int =  ( 2 )

print ( type ( tup_one ) ) 
print ( type ( tup_int ) )

'''
<class 'tuple'>
<class 'int'>
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

access tuple

tup1 =  ( 'Google' ,  'Runoob' ,  1997 ,  2000 ) 
tup2 =  ( 1 ,  2 ,  3 ,  4 ,  5 ,  6 ,  7  )
 
print  ( "tup1[0]: " , tup1 [ 0 ] ) 
print  ( "tup2[1:5]: " , tup2 [ 1 : 5 ] )

'''
tup1[0]: Google
tup2[1:5]: (2, 3, 4, 5)
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

modify tuple

Although the elements in the tuple cannot be modified, the tuples can be concatenated and combined

tup1 =  ( 12 , 23 , 45 , 6.6 ) 
tup2 =  ( 'abc' , 'def' )

tup1 = tup1 + tup2
 print ( tup1 )

'''
(12,23,45,6.6,'abc','def')
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

delete tuple

Although the elements in the tuple cannot be modified (including deletion), the entire tuple can be deleted

tup =  ( 'Google' ,  'Runoob' ,  1997 ,  2000 )
 
print  ( tup ) 
del tup
 print  ( "Deleted tuple tup : " ) 
print  ( tup ) 
'''
('Google', 'Runoob', 1997, 2000)
Deleted tuple tup:
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 6, in <module>
    print (tup)
NameError: name 'tup' is not defined
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Tuple built-in functions

len(tuple) counts the number of elements in a tuple.

max(tuple) returns the maximum value of the elements in the tuple.

min(tuple) returns the minimum value of the elements in the tuple

tuple(iterable) converts an iterable series to a tuple.

Tags: The road to Python learning----Introduction to tuples

Topics in Python python

Related: The road to Python learning----Introduction to tuples