Python tuple explanation

 

Python tuple explanation

Python tuple explanation

Directory list

  1.   Definition of tuple
  2. Tuple creation
  3. Accessing values in tuples
  4. update tuple
  5. Delete tuple element
  6. Basic tuple operation
  7. Index, slice and matrix
  8. Tuple loop traversal
  9. Tuples and formatted strings
  10. Conversion between tuples and lists
  11. Built in tuple function

Reference documents: https://www.runoob.com/python/python-tuples.html

1. Definition of tuple

1.1 definition of tuple:

Tuples are similar to lists. They can store any data type, but the elements in tuples cannot be changed arbitrarily without adding, deleting or changing

1.2 features:

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

Tuples use parentheses (), and lists use square brackets []

The creation of tuples is very simple. Just add elements in parentheses and separate them with commas

The index of tuples starts at 0

 

2. Tuple creation

2.1 variable name = ()

t=('I','love','python')
print(t)
print(type(t))

result:

('I','love','python')
<class 'tuple'>

2.2 using the built-in function tuple ()

t1=tuple('I','love','python',123,435)
print(t1)
print(type(t1)

Results:

('I','love','python',123,435)
<class 'tuple'>

2.3 if there is only one element in the tuple, there must be a comma

#Standard writing
t3=(1,)
t4=('python',)  

print(t3,t4)

#You can also write like this (not recommended)

t5=(50)
print(t5)

Results:

(1,)('python')
t5

2.4 creating empty tuples

print(tuple())    #First kind
t6=tuple()        #Second
empty_tuple=()    #Third
print(t6,type(t6)
print(type(empty_tuple))

result:

()
() <class 'tuple'>
()

3. Accessing values in tuples

Like a list, we can use an Index to access an element in a tuple (the value of an element is obtained), or we can use a slice to access a group of elements in a tuple (a new child tuple is obtained)

The format of accessing tuple elements using index is:

tuple_name[i]
#Among them, tuple_name indicates the tuple name, i indicates the index value, and the tuple index can be positive or negative

Code demonstration:

t=tuple('https://www.csdn.net')
#Use an index to access an element in a tuple
print(t[10])    #Use positive index
print(t[-10])    #Use negative index

 

The result is:

w
.

The format of accessing tuple elements using slices is:

Name_tuple[start : end : step]
#Where, start represents the start index, end represents the end index, and step represents the step size

Code demonstration:

t=tuple('https://www.csdn.net')
print(t[3:5:])      #Use positive slice

print(t[4:5:2])     #Start: 4 end: 5 step: 2 specify the start and end and step size

print(t[-3:-1])     #Use negative slices

print(t[:2])        #Slicing operation

print(t[0:-1])      #break off both ends

print(t[::2])       #Reverse order

print(t[::2])       #One at a time

print(t[::])        #Take all

The result is:

('p', 's')
('s',)
('n', 'e')
('h', 't')
('h', 't', 't', 'p', 's', ':', '/', '/', 'w', 'w', 'w', '.', 'c', 's', 'd', 'n', '.', 'n', 'e')
('h', 't', 's', '/', 'w', 'w', 'c', 'd', '.', 'e')
('h', 't', 's', '/', 'w', 'w', 'c', 'd', '.', 'e')
('h', 't', 't', 'p', 's', ':', '/', '/', 'w', 'w', 'w', '.', 'c', 's', 'd', 'n', '.', 'n', 'e', 't')

4. Update / modify tuples

Tuples are immutable, which means that we cannot update or change the value of tuple elements, but we can use part of existing tuples to create new tuples

Code demonstration:

tuple1=('abc','efg','asd')
tuple2=(1,2,3,4,5,6)
c=tuple1+tuple2
print(c)
print(type(c))

The result is:

('abc', 'efg', 'asd', 1, 2, 3, 4, 5, 6)
<class 'tuple'>

5. Delete tuple element

The element value in the element is not allowed to be deleted, but we can use the del statement to delete the entire tuple

tup=('I','love','Python',234,54,765)
print (tup)
del tup
print("After deleting tup :")
print (tup)

The result is:

('I', 'love', 'Python', 234, 54, 765)
After deleting tup :

Traceback (most recent call last):
  File "G:/Python/learn02/demo.py", line 15, in <module>
    print (tup)
NameError: name 'tup' is not defined

6. Basic tuple operation

6.1 repetition of tuples

users=('root','redhat','inux')
#repeat
print (users  *3)

The result is:

('root', 'redhat', 'inux', 'root', 'redhat', 'inux', 'root', 'redhat', 'inux')

6.2 connection of tuples

tuple=(1,2,3,4,5)
print(tuple + ('123','123'))

The result is:

(1, 2, 3, 4, 5, '123', '123')

6.3 member operators

#Member operator
hub=('redhat','Centos','Ubtun','Winning Qilin')
passwds=('123','456','789')
print('unix' in hub)
print('redhat' not in hub)

#iteration
for kebi in hub:
       print(kebi)

for index,kebi in enumerate(hub):
    print('The first%d Users: %s' % (index+1,kebi))


for kebi,passwd in zip(hub,passwds):
    print(kebi,':',passwd)

The result is:

False
False
redhat
Centos
Ubtun
 Winning Qilin
 First user: redhat
 2nd user: Centos
 3rd user: Ubtun
 The fourth user: Winning Qilin
redhat : 123
Centos : 456
Ubtun : 789


7. Index, slice and matrix

Since tuples are sequences, indexes, and slices that work the same way as lists, suppose you enter the following values:

Y=('c','c++','python','GO')
print(Y[2])
print(Y[-2])
print(Y[1:])

The result is:

python
python
('c++', 'python', 'GO')

8. Tuple loop traversal

tup = ('millet', 'SKYWORTH', 'Hisense','Konka','Changhong')
for tv in tup:
    print(tv)


The result is:

millet
 SKYWORTH
 Hisense
 Konka
 Changhong

9. Tuples and formatted strings

The parentheses and contents after formatting are essentially tuples; We can first define a tuple, and then format the% tuple, which can also be output. At the same time, we can even take out the function in the print bracket, define it as a variable, and output it in print

name='zhangsan'
age=12
heigh=181
print("%s What is your age %d,Height is %d" % (name,age,heigh))

userinfo = ('zhansan',20,182)
print("%s What is your age %d,Height is %d" %(userinfo[0],userinfo[1],userinfo[2]))

#You can also write like this
print("%s What is your age %d,Height is %d" % userinfo)
info ="%s What is your age %d,Height is %d" % userinfo
print(info)

The result is:

zhangsan My age is 12 and my height is 181
zhansan My age is 20,Height is 182
zhansan My age is 20 and my height is 182
zhansan My age is 20 and my height is 182

10. Conversion between tuples and lists

Convert other data types to tuple types, such as string, list, tuple, etc

#Convert string to tuple
tup1 = tuple("hello",)
print(tup1)
#Convert list to tuple
list1 = ['Python', 'Java', 'C++', 'JavaScript']
tup2 = tuple(list1)
print(tup2)
#Convert dictionary to tuple
dict1 = {'a':100, 'b':42, 'c':9}
tup3 = tuple(dict1)
print(tup3)
#Convert interval to tuple
range1 = range(1, 6)
tup4 = tuple(range1)
print(tup4)

The result is:

('h', 'e', 'l', 'l', 'o')
('Python', 'Java', 'C++', 'JavaScript')
('a', 'b', 'c')
(1, 2, 3, 4, 5)

 11. Built in tuple function

Tuple function:
    cmp (tuple1,tuple2) compares the elements of two tuples
    len(tuple) gives the total length of tuples
    max (tuple) returns the maximum value item from the tuple
    min (tuple) returns the maximum value item from the tuple
    tuple (seq) converts a list into tuples

Code demonstration:

tup1 = (1, 2, 3, 4, 5)
tup3 = (1, 2, 3, 4)
tup2 = ('a', 'b', 'c', 'd', 'e')

print (cmp(tup1, tup2))
print (cmp(tup1, tup3))
print (len(tup1))
print (len(tup2))
print (max(tup1))
print (max(tup2))
print (min(tup1))

The result is:

5
5
5
e
1

Your praise is my biggest motivation

Keywords: Python Programming

Added by Fehnris on Sun, 30 Jan 2022 05:32:25 +0200