Home >Backend Development >Python Tutorial >What is the usage of lists in python
List (list) is the most commonly used Python data type, which can appear as a comma-separated value within square brackets.
The data items in the List do not need to be of the same type. The operations that can be performed include indexing (the first index is 0, the second index is 1, and so on), slicing, addition, multiplication, Check members etc.
To create a list, just enclose the different data items separated by commas in square brackets, as shown below:
list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1,2,3,4,5] list3 = ["a", "b", "c", "d"]
Like the index of the string, the List index starts from 0 , you can perform operations such as interception and combination.
Access the values in the list
Use subscript index to access the values in the list, you can also use square brackets to intercept characters, as shown below:
list1[0] ; #取第一个元素 list1[-1] # 取最后一个元素 list1[ : ] 或者 list1[ : len(list1)] # 取所有列表元素 list1[0 : n] # 从第0号取到n-1号元素
The output is as follows:
##Update list
You can modify or update the data items of the list, or you can use the append() method to add list items, as shown below:list1[0] = 'D' # 修改元素值 list1.append('E') # 列表添加元素 list1.insert(0 , 'F') # 在某处插入元素Specific example:
Delete list elements
You can use the del statement to delete elements of the list.del list1[0] # 删除元素
list1.remove('1') # 移除第一次出现的元素
list1.pop() # 移出元素,默认从最后移出,返回该元素值;括号中可加入元素索引值来移除
Python List Script Operator
The operators of list pairs and * are similar to strings. The symbol is used to combine lists, and the * symbol is used to repeat lists.Python List Functions & Methods
Python contains the following functions: Python includes the following methods: python learning network, a large number of freepython video tutorials, welcome to learn online!
The above is the detailed content of What is the usage of lists in python. For more information, please follow other related articles on the PHP Chinese website!