The most common problems with Python lists

List is one of the most used data results in Python. How to operate lists efficiently is the key to improve code efficiency. This paper summarizes some of the most common problems of Python lists, hoping to help you.

1. How to access subscript index in iteration 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 where the first element of an element starts, default to 0, or start from 1:

What I don't know in the process of learning can be added to me?
python learning communication deduction qun, 784758214
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn
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 appending a data as a new element to the end of the list, and its parameters can be arbitrary objects.

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

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

The extension parameter must be an iterative object, meaning 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 if the list is empty

Ordinary edition:

if len(items) == 0:
    print("Empty list")

perhaps

if items == []:
    print("Empty list")

Elegant Edition:

if not items:
    print("Empty list")

4. How to Understand Slices

Slices are used to get a subset of the specified norms in the list, and the syntax is very simple

items[start:end:step]

Elements from start to end-1. Step represents step size, default is 1, means continuous acquisition, if step 2 means every other element acquisition.

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

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

>>> a[3:8:2] # Elements between positions 3 to 8, retrieved every other element
[4, 6, 8]

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

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

>>> a[::]  # All of them are omitted, which is equivalent to a list of copies, which belong to shallow copies.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5. How to copy a list object
The first method is:

new_list = old_list[:]

The second method:

new_list = list(old_list)

The third method is:

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 not only support positive but also negative numbers. Positive numbers indicate that the index starts from the left side of the list, negative numbers indicate that the index starts from the right side of the list, and 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 lists

There are two ways to sort lists. One is the way that lists come with, and the other is the built-in sorted function. Complex data types can be sorted by specifying key parameters. A list of dictionaries, sorted according to the age field of dictionary elements:

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 sort method, which is used to reorder the original list, specifying key parameters, key is an anonymous function, item is the dictionary element in the list, we sort according to the age in the dictionary, the default is to sort in ascending order, specifying 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 don't want to change the original list, but instead generate a new ordered list object, you can have the built-in 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 elements from the list

There are three ways to delete elements from a list

remove removes an element and only removes the element that appears for the first time

>>> 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 removes an element according to the specified location

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

# Throw an exception to IndexError when you exceed the following table index of the list
>>> 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 the removed element

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

# Similarly, throw an exception to IndexError when it exceeds the index of the following table in the list
>>> 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]

Lists overload + operators, so that + not only supports numerical addition, but also supports the addition of two lists. As long as you implement the _add_ operation of the object, any object can achieve the operation, such as:

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 retrieve an element in a list

What I don't know in the process of learning can be added to me?
python learning communication deduction qun, 784758214
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from zero foundation, and what to learn
import random
items = [8, 23, 45, 12, 78]

>>> random.choice(items)
78
>>> random.choice(items)
45
>>> random.choice(items)
12

Keywords: Python Lambda

Added by rrn on Tue, 27 Aug 2019 16:07:19 +0300