Pre initialization of list content and length in Python

If you want to set the same initial value and desired length

>>> a=[None]*4
>>> print(a)
[None, None, None, None]

If we know the length of the list in advance, we can initialize the list of that length in advance, and then assign values to each list, which will be faster than each time list.append () more efficient.

If you want the sequence initial value, you can use the range function, but note that the range function returns an iterative object, which needs to be converted into a list

>>> b=list(range(10))
>>> print(b)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> b=range(10)
>>> print(b)
range(0, 10)

If you want to eliminate unwanted data, you can use the list derivation

>>> c=[i for i in range(10) if i%2==0 and i<8]
>>> print(c)
[0, 2, 4, 6]

Life is short, You need Python~

Read More: