Python Tutorial, Release 3.9.5 5.1.2 Using Lists as Queues 5.1.3 List Comprehensions It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first- out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one). To implement a queue, use$_{collections.deque}$ which was designed to have fast appends and pops from both ends. For example: List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. For example, assume we want to create a list of squares, like: Note that this creates (or overwrites) a variable named$_{x}$ that still exists after the loop completes. We can calculate the list of squares without any side effects using: or, equivalently: squares =list(map( lambda x: x**2,range(10 ))) squares =[x**2 for x in range(10 )] which is more concise and readable. A list comprehension consists of brackets containing an expression followed by a$_{for}$ clause, then zero or more$_{for}$ or$_{if}$ clauses. The result will be a new list resulting from evaluating the expression in the context of the$_{for}$ and$_{if}$ clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal: and it’s equivalent to: (continues on next page) 33 5.1. More on Lists >>> combs =[] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x !=y: ... combs.append((x, y)) ... >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x !=y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, >>> squares =[] >>> for x in range(10 ): ... squares.append(x **2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> from collectionsimport deque >>> queue =deque(["Eric","John","Michael "]) >>> queue.append( "Terry") # Terry arrives >>> queue.append( "Graham ") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])