Advanced features of python -- slicing and iteration

Posted by richtux on Mon, 28 Feb 2022 02:54:53 +0100


In Python, the more code is not the better, but the less the better. The code is not as complex as possible, but as simple as possible.
Based on this idea, let's introduce the very useful advanced features in Python, the functions that can be realized by one line of code, and never write five lines of code. Keep in mind that the less code you have, the more efficient your development will be.

1, Slice

Taking some elements of a list or tuple is a very common operation.

1. Take the first three elements in a list

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
#Method 1
[L[0], L[1], L[2]]
#Method 2
r = []
n = 3
for i in range(3):

For this kind of operation that often takes the specified index range, using the loop is very troublesome. A simpler method is to use the Slice operator provided by python:

#Indicates that the index is retrieved from 0 (0: L[:3] can be ignored), but index 3 is not included
L[0 : 3]

In the List, L[-1] can take the penultimate element, and it also supports the penultimate slice. The index of the penultimate element is - 1:

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[-2:] #['Bob', 'Jack']
L[-2 : -1] #['Bob']

You can easily take out a sequence of numbers by slicing:

L = list(range(100))
L[10:20] #[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
L[:10:2] #Take one from every two of the first 10 numbers [0,2,4,6,8]
L[::5] #All numbers, one for every five [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
#[:] you can copy a list as it is

2. Use slices to get the elements in tuple

Tuple is also a list. The only difference is that tuple is immutable. Therefore, tuple can also be sliced, but the result of the operation is still tuple

(0, 1, 2, 3, 4, 5)[:3] #(0,1,2)

3. String slicing

The string 'xxx' can also be regarded as a list, and each element is a character.

Therefore, a string can also be sliced, but the result of the operation is still a string:

'ABCDEFG'[:3] #'ABC'
'ABCDEFG'[::2] #'ACEG'

Python does not have a string interception function. It only needs one operation to slice, which is very simple

4. Practice

Using slicing operation, implement a trim() function to remove the spaces at the beginning and end of the string. Be careful not to call str's strip() method:
Method 1

# -*- coding: utf-8 -*-
def trim(s):
    # Consider s as' 'or all spaces
    n = len(s)
    if s == n*(' '):
        return ''
    #Consider slicing the first and last characters directly, and using a loop to eliminate ''
        while s[0] == ' ' :
            s = s[1:]
        while s[-1] == ' ' :
            s = s[:-1] 
        return s

Method 2

# s[0:1] ensures that when s is' ', it will not enter the loop and there is no syntax error. If s[0] is used, it will make an error when s = =' '
def trim(s):
    while s[0:1] == ' ':

            s = s[1:]

    while s[-1:] == ' ':

            s = s[:-1]
    return s

2, Iteration

If a list or tuple is given, we can traverse the list or tuple through the for loop, which is called Iteration.

Python's for loop can be used not only on list s or tuple s, but also on other iteratable objects.

As long as it is an iteratable object, it can iterate whether there is a subscript or not.

1. dict iteration

For example, dict can iterate:

d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    print(key) #a b c or a c b ...

Because the storage of dict is not arranged in the order of list, the order of iterative results is likely to be different.
By default, the key of dict iteration is. If you want to iterate over value, you can use for value in d.values(). If you want to iterate over key and value at the same time, you can use for k, v in d.items()

2. String iteration

Since the string is also an iteratable object, it can also act on the for loop:

for ch in 'ABC':
    print(ch) # A B C

When we use the for loop, as long as we act on an iteratable object, the for loop can run normally, and we don't care whether the object is a list or other data types.

3. Iteratable type: judge the iteratable object

Through collections The iteratable type of ABC module determines whether an object is an iteratable object.

>>> from import Iterable
>>> isinstance('abc',Iterable) # Is str iterative
>>> isinstance([1,2,3],Iterable) # Is str iterative
>>> isinstance(123,Iterable) # Is the integer iteratable

4.enumerate function: iterate the index and the element itself at the same time

Python's built-in enumerate function can turn a list into an index element pair, so that the index and the element itself can be iterated simultaneously in the for loop

>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
0 A
1 B
2 C

It is common to reference two variables simultaneously in python:

>>> for x,y in [(1,1),(2,4),(3,9)]:
...     print(x, y)
1 1
2 4
3 9

5. Practice

# Please use iteration to find the minimum and maximum values in a list and return a tuple:
# -*- coding: utf-8 -*-
def findMinAndMax(L):
# Consider setting a comparison initial value max min = L[0]
    if L == []:
        return (None, None)
        max = L[0]
        min = L[0]
        for i in L:
            if i >= max:
                max = i
            elif i <= min:
                min = i
        return (min, max)


1. None type in Python

None type: indicates that the value is an empty object. A null value is a special value in Python, represented by none.
None cannot be understood as 0, because 0 is meaningful, while none is a special null value, and the type of none is NoneType.

None feature

  • None does not support any operations and does not have any built-in methods
  • None always returns False when compared with any other data type
  • None has its own data type, NoneType. You cannot create other NoneType objects (it has only one value, none). None is different from 0, empty list and empty string
    -You can assign a value of None to any variable, or you can assign a value to a variable with a value of None
    None has no attributes like len and size. To judge whether a variable is none, use it directly
    Original link:

2.python error: typeerror: cannot unpack non Iterable int object

  1. Ensure that the number of function return values is consistent, that is, the number of function return values should be consistent with the number of calling function return values
  2. If you use an IF statement, make sure that the number of return values in if and else is the same!
  3. When assigning list elements to other variables, parallel assignment will report an error;
>>> L = (1,2,3)
>>> max, min = L[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot unpack non-iterable int object

Solution: separate assignment

>>> L = (1,2,3)
>>> max = L[0]
>>> min = L[0]

Topics: Python Back-end