Introduction
topping = ['mushroom', 'pineapple', 'bacon', 'onion']
print(topping)
# ['mushroom', 'pineapple', 'bacon', 'onion']
- List is a compatible abstract data type. Data structure knowledge is required on how to realize it; can just directly understand and operate here, it is very easy after all.
- List in Python is somewhat similar to the array of languages like C (actually more convenient than the array operations, because of the integration of a large number of functions and methods)
Accessing list
- Sequential access (pointer start at 0 and end at the last element position - 1)
- Reverse order access ([-1] is the last element, and so on)
topping = ['mushroom', 'pineapple', 'bacon', 'onion']
print(topping[0])
print(topping[-1])
Output
mushroom
onion
Modify, insert and delete
These are permanent operations.
There is a deletion worth mentioning: the "stack" type pop deletion; the last element is popped in a non-specified position, and pop() is a "method" (pop the last element).
topping = ['mushroom', 'pineapple', 'bacon', 'onion']
del topping[0]
topping.remove('onion')
print(topping)
print()
topping = ['mushroom', 'pineapple', 'bacon', 'onion']
pop_topping = topping.pop()
print(pop_topping)
print(topping)
Output
['pineapple', 'bacon']
onion
['mushroom', 'pineapple', 'bacon']
Organization list
- sort() sorting, which is divided into parameters with and without parameters
- reverse() method implements reverse (directly reverse order of the list)
ordering = [4, 2, 1, 3]
ordering.sort()
ordering.sort(-1)
print(ordering)
print()
ordering.reverse()
print(ordering)
ordering.reverse()
Output
[4, 3, 2, 1]
[1, 2, 3, 4]
Getting the length of the list
The len() function gets the length of the list.
ordering = [4, 2, 1, 3]
print(len(ordering))
Output
4
Comments 1 comment
Blogger Richard Lu
666