Python basis of 3 - tuples

Tuples and list difference

  1. Python tuples and a list of similar, except that the list can be modified, a tuple can not be modified
  2. Tuples with parentheses ()defined list of square brackets []is defined
  3. Tuples can not be modified, the list may be modified

Create a tuple

Only in parentheses ()added contents and comma ,separated, the following example

emp_tup = ('张三','李四','王五')
print(emp_tup)
# 运行结果:('张三', '李四', '王五')

Note: When only one tuple element, should be added after the element ,
if it is not followed by a comma ,is used as the processing operator, the following example is the correct approach.

emp_tup = ('张三',)
print(emp_tup)
# 运行结果:('张三',)

Tuple values

Tuples and lists, the use of upper and lower standard values

emp_tup = ['张三','李四','王五','赵六']
print(emp_tup[2])
# 运行结果: 王五
emp_tup = ['张三','李四','王五','赵六']
print(emp_tup[-1])
# 运行结果: 赵六

Tuple modification

Tuples can not be modified, but it can be spliced ​​to the tuple

num1 = (10,20,30)
num2 = (40,50,60)
num_all = num1 + num2
print(num_all)
# 运行结果:(10, 20, 30, 40, 50, 60)

Tuples transfer list

num = (10,20,30)
num_list = list(num)
print(num)
print(num_list)

# 运行结果:
'''
(10, 20, 30)
[10, 20, 30]
'''

Guess you like

Origin www.cnblogs.com/dazhi-blog/p/11520741.html