Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
Sometimes you need to have a queue in your program, i. e. a container where you put elements from one side and remove them from another. list can be such a container: In : lst = [1, 2, 3] In : lst.pop() Out: 3 In : lst Out: [1, 2] In : lst[:0] = [4] # push In : lst Out: [4, 1, 2] However, using list doesn't only look eerie (look at that push), but also is quite inefficient. In : lst = [0] * 10_000_000 In : %timeit lst[:0] = [1] 9.5 ms ± 111 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In : %timeit lst.pop() 84.3 ns ± 4.01 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) As you can see, on my machine pop is 100 times faster than “push”. This is how list works: elements can be easily added to or removed from the end of the list, but to remove the first element, Python needs to create a new list from scratch. What you really want to use for this problem is collections.deque. It's designed to be used as a queue: In : d = deque([1] * 100_000_000) In : %timeit d.popleft() 65 ns ± 0.436 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)