List is one of the most frequently used data results in Python. How to operate list efficiently is the key to improve code operation efficiency. This article lists 10 common list operations, hoping to help you.
1. How to access list subscript index when iterating list
Ordinary Edition:
items = [8, 23, 45] for index in range(len(items)): print(index, "-->", items[index]) >>> 0 --> 8 1 --> 23 2 --> 45
Elegant Edition:
for index, item in enumerate(items): print(index, "-->", item) >>> 0 --> 8 1 --> 23 2 --> 45
enumerate can also specify the starting point of the first element of an element, which is 0 by default, or 1:
for index, item in enumerate(items, start=1): print(index, "-->", item) >>> 1 --> 8 2 --> 23 3 --> 45
2. What is the difference between append and extend methods
Append means to append a data as a new element to the end of the list. Its parameters can be any object
x = [1, 2, 3] y = [4, 5] x.append(y) print(x) >>> [1, 2, 3, [4, 5]]
The parameter of extend must be an iterative object, which means that all elements in the object are appended to the back of the list one by one
x = [1, 2, 3] y = [4, 5] x.extend(y) print(x) >>> [1, 2, 3, 4, 5] # Equivalent to: for i in y: x.append(i)
3. Check whether the list is empty
Ordinary Edition:
if len(items) == 0: print("Null list") //perhaps if items == []: print("Null list")
Elegant Edition:
if not items: print("Null list")
4. How to understand slice
Slicing is used to get a subset of the specified norms in the list. The syntax is very simple
items[start:end:step] Elements from start to end-1. Step represents step size. The default value is 1, which means continuous acquisition. If step is 2, it means every other element acquisition. a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>A [3:8] ා elements between the 3rd and 8th positions [4, 5, 6, 7, 8] >>>A [3:8:2] ා the elements between the 3rd and 8th positions are obtained every other element [4, 6, 8] >>>A [: 5] ා omitting start means starting from element 0 [1, 2, 3, 4, 5] >>>A [3:] omit the end representation to the last element [4, 5, 6, 7, 8, 9, 10] >>>A [::] ාාාාis equivalent to copying a list. This kind of copy belongs to shallow copy [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5. How to copy a list object
The first method:
new_list = old_list[:]
The second method:
new_list = list(old_list)
The third method:
import copy # Shallow copy new_list = copy.copy(old_list) # Deep copy new_list = copy.deepcopy(old_list)
6. How to get the last element in the list
The elements in the index list support not only positive numbers but also negative numbers. A positive number indicates that the index starts from the left side of the list, and a negative number indicates that the index starts from the right side of the list. There are two ways to get the last element.
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> a[len(a)-1] 10 >>> a[-1] 10
7. How to sort the list
There are two ways to sort a list, one is sort, which comes with the list, and the other is sort, which is a built-in function. Complex data types can be sorted by specifying the key parameter. A list composed of dictionaries, sorted according to the age field in the dictionary element:
items = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}, {"name": 'cater', 'age': 20}] items.sort(key=lambda item: item.get("age")) print(items) >>> [{'age': 10, 'name': 'Bart'}, {'age': 20, 'name': 'cater'}, {'age': 39, 'name': 'Homer'}]
The list has the sort method, which is used to reorder the original list. The key parameter is specified. The key is an anonymous function, and the item is a dictionary element in the list. We sort according to the age in the dictionary. By default, we sort in ascending order, and specify reverse=True in descending order
items.sort(key=lambda item: item.get("age"), reverse=True) >>> [{'name': 'Homer', 'age': 39}, {'name': 'cater', 'age': 20}, {'name': 'Bart', 'age': 10}]
If you do not want to change the original list, but to generate a new ordered list object, you can build in the function sorted, which returns the new list
items = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}, {"name": 'cater', 'age': 20}] new_items = sorted(items, key=lambda item: item.get("age")) print(items) >>> [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}, {'name': 'cater', 'age': 20}] print(new_items) >>> [{'name': 'Bart', 'age': 10}, {'name': 'cater', 'age': 20}, {'name': 'Homer', 'age': 39}]
8. How to remove the elements in the list
There are three ways to delete elements from a list
remove removes an element and only the first occurrence
>>> a = [0, 2, 2, 3] >>> a.remove(2) >>> a [0, 2, 3] # If the element to be removed is not in the list, a ValueError exception is thrown >>> a.remove(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list· del Remove an element according to the specified location >>> a = [3, 2, 2, 1] # Remove first element >>> del a[1] [3, 2, 1] # An IndexError exception is thrown when the following table index of the list is exceeded >>> del a[7] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range
Pop is similar to del, but the pop method can return removed elements
>>> a = [4, 3, 5] >>> a.pop(1) 3 >>> a [4, 5] # Similarly, an IndexError exception is thrown when the following table index of the list is exceeded >>> a.pop(7) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop index out of range
9. How to connect two lists
listone = [1, 2, 3] listtwo = [4, 5, 6] mergedlist = listone + listtwo print(mergelist) >>> [1, 2, 3, 4, 5, 6]
The list implements the operator overload of + so that + not only supports numerical addition, but also supports the addition of two lists. As long as you implement the add operation of an object, any object can implement the + operation, for example:
class User(object): def __init__(self, age): self.age = age def __repr__(self): return 'User(%d)' % self.age def __add__(self, other): age = self.age + other.age return User(age) user_a = User(10) user_b = User(20) c = user_a + user_b print(c) >>> User(30)
10. How to randomly obtain an element in the list
import random items = [8, 23, 45, 12, 78] >>> random.choice(items) 78 >>> random.choice(items) 45 >>> random.choice(items) 12