Lists are one of the most commonly used data results in Python. How to efficiently manipulate lists is the key to making your code run more efficiently. This article has listed 10 common list operations that you hope will help you.



1. How do I access the list subindex when iterating over a list

Normal version:

items = [8, 23, 45]
for index in range(len(items)):
    print(index, "-- >", items[index])

>>>
0 --> 8
1 --> 23
2 --> 45Copy the code

Elegant version:

for index, item in enumerate(items):
    print(index, "-- >", item)

>>>
0 --> 8
1 --> 23
2 --> 45Copy the code

Enumerate also specifies the starting point for 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 --> 45Copy the code

What is the difference between the append and extend methods

Append means to append some data to the end of the list as a new element, and it can take any object

x = [1, 2, 3]
y = [4, 5]
x.append(y)
print(x)

>>>
[1, 2, 3, [4, 5]]Copy the code

The extend argument must be an iterable that appends all elements of that object one by one to the end of the list

x = [1, 2, 3]
y = [4, 5]
x.extend(y)
print(x)

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

# is equivalent to:
for i in y:
    x.append(i)Copy the code

3. Check whether the list is empty

Normal version:

if len(items) == 0:
    print(Empty list) orif items == []:
    print(Empty list)
Copy the code

Elegant version:

if not items:
    print(Empty list)Copy the code

4. How to understand slicing

Slicing is used to get a subset of a specified norm in a list, and the syntax is very simple

items[start:end:step]Copy the code

Elements between the start and end-1 positions. Step indicates the step size. The default value is 1, indicating that the value is obtained continuously. If step is 2, indicating that the value is obtained every other element.

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a[3:8] # Elements between positions 3 and 8
[4, 5, 6, 7, 8]

>>> a[3:8:2] # fetch elements between positions 3 and 8 every other element
[4, 6, 8]

>>> a[:5]   # omitting start means starting at the 0th element
[1, 2, 3, 4, 5]

>>> a[3:]  # omitting end means to go to the last element
[4, 5, 6, 7, 8, 9, 10]

>>> a[::]  # omit is equivalent to copying a list, which is a shallow copy
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Copy the code

How do I copy a list object

The first method:

new_list = old_list[:]Copy the code

The second method:

new_list = list(old_list)Copy the code

The third method:

import copy
# shallow copy
new_list = copy.copy(old_list)
# deep copy
new_list = copy.deepcopy(old_list)Copy the code

How do I get the last element in the list

Elements in an indexed list support both positive and negative numbers, where the index starts from the left side of the list and negative numbers start 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]
10Copy the code

7. How to sort the list

There are two ways to sort a list. One is sort, which comes with lists, and the other is sorted, which is a built-in function. Complex data types can be sorted by specifying the key parameter. A list of dictionaries, sorted by 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'}]
Copy the code

The list has a sort method that resorts the original list, specifying the key argument, which is an anonymous function, and item, which is the dictionary element in the list. We sort by the age of the dictionary, which is ascending by default, and reverse=True, which is descending

items.sort(key=lambda item: item.get("age"), reverse=True)

>>>
[{'name': 'Homer'.'age': 39}, {'name': 'cater'.'age': 20}, {'name': 'Bart'.'age': 10}]
Copy the code

If you don’t want to change the original list and instead generate a new ordered list object, you can have a built-in function called sorted that 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}]Copy the code

8. How to remove an element from a list

There are three ways to remove 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, ValueError is raised
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not inThe list,Copy the code

Del removes an element at the specified location

>>> a = [3, 2, 2, 1]
Remove the first element
>>> del a[1]
[3, 2, 1]

Raise IndexError when the index of the lower table 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 rangeCopy the code

Pop is similar to del, but the pop method returns the removed element

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

Also, raise IndexError when the index of the lower table 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
Copy the code

9. How to join two lists

listone = [1, 2, 3]
listtwo = [4, 5, 6]

mergedlist = listone + listtwo

print(mergelist)
>>>
[1, 2, 3, 4, 5, 6]
Copy the code

Lists implement operator overloading of +, making it possible to add not only numeric values but also two lists. Any object can implement + as long as you implement __add__ on the object, 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)Copy the code

How do I randomly fetch an element from a list

import random
items = [8, 23, 45, 12, 78]

>>> random.choice(items)
78
>>> random.choice(items)
45
>>> random.choice(items)
12Copy the code

Life is short, I use Python!!