The difference between list list and tuple in python

the difference:

Both lists and tuples are in the form of sequences and can store data. What is the difference between them?

The list is a dynamic array, expressed in square brackets, can continue to add and delete data, and is variable.

A tuple is a static array, expressed in parentheses, once the data is created, it cannot be changed.

The methods of creating, accessing and adding elements to the list are as follows:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

if __name__ == '__main__':
    # 创建列表
    test_l = [1, 2, 3, 4, 5]
    # 输出整个列表
    print(test_l)
    # 输出列表前两项的值
    print(test_l[0:2])
    # 添加元素
    test_l.append(6)
    # 输出整个列表
    print(test_l)

output:

[1, 2, 3, 4, 5]
[1, 2]
[1, 2, 3, 4, 5, 6]

The creation and access methods of tuples are as follows: 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

if __name__ == '__main__':
    # 创建元组
    test_t = (1, 2, 3, 4, 5)
    # 输出整个元组
    print(test_t)
    # 输出元组前两项的值
    print(test_t[0:2])

output:

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

scenes to be used:

When you want to create data that will not be easily rewritten, you can use tuples to store it; when the data needs to be changed frequently, you can use lists to store it.

Guess you like

Origin blog.csdn.net/kevinjin2011/article/details/129365986