5 Best Ways to Check if Queue Elements Are Pairwise Consecutive in Python

Rate this post

πŸ’‘ Problem Formulation: Imagine having a queue of numbers and needing to verify if each pair of elements is consecutive. We’re interested in knowing whether elements in a queue follow each other directly in the sequence, like (1,2), (3,4), etc. For example, given a queue with the input elements [4, 5, -2, -1, 10, 11], we want our methods to confirm that these elements are pairwise consecutive.

Method 1: Iterative Comparison

This method involves iterating over the queue and comparing each pair of elements. The function will iterate through the elements by twos and check if the second element is one more than the first. If all pairs pass this check, the function returns True, otherwise False.

Here’s an example:

from queue import Queue

def are_pairwise_consecutive(queue):
    temp_queue = Queue()
    while not queue.empty():
        n1 = queue.get()
        if not queue.empty():
            n2 = queue.get()
            if abs(n1 - n2) != 1:
                return False
    return True

# Example usage
q = Queue()
for num in [4, 5, -2, -1, 10, 11]:


Output: True

This snippet creates a queue and fills it with the given elements. The are_pairwise_consecutive function compares each pair of elements inside a loop to check for the consecutive property. It handles even the case where the number sequence has negative values.

Method 2: Using a List

Convert the queue to a list and perform indexing to check consecutiveness. This method allows random access to elements, which makes comparisons straightforward but uses additional space for the list.

Here’s an example:

def are_elements_consecutive(queue):
    elements_list = list(queue.queue)
    for i in range(0, len(elements_list) - 1, 2):
        if abs(elements_list[i] - elements_list[i+1]) != 1:
            return False
    return True

# Example usage with a Queue object
q = Queue()
for num in [4, 5, -2, -1, 10, 11]:


Output: True

This code converts the queue into a list and checks if each pair of elements is consecutive by iterating over the list. Notice that pairs are accessed using their index, which allows an efficient comparison operation.

Method 3: Deque for In-Place Checking

Utilize a deque (double-ended queue) to efficiently pop elements from both ends. This method provides constant time operations for removing elements from the queue’s front and back, allowing us to check for consecutiveness without copying the queue.

Here’s an example:

from collections import deque

def are_elements_consecutive(deq):
    while len(deq) > 1:
        if abs(deq.pop() - deq.pop()) != 1:
            return False
    return True

# Example usage with a deque
dq = deque([4, 5, -2, -1, 10, 11])


Output: True

The code uses a deque to remove elements from the end of the queue two at a time and checks their consecutiveness. Using deque operations can be faster than list or queue operations for this purpose.

Method 4: Using Itertools

The itertools module helps create an iterator that returns pairs of elements. This method leverages the power of itertools to pair up elements and verify consecutive properties without explicitly managing the looping construct.

Here’s an example:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s2,s3), (s4, s5), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

# Example usage with a list representing a queue
queue_list = [4, 5, -2, -1, 10, 11]
pairs = pairwise(queue_list)

print(all(abs(x - y) == 1 for x, y in pairs))

Output: True

This code creates pairs of adjacent elements and then uses a generator expression within the all() function to check if all pairs are consecutive. It elegantly uses itertools to handle the pairing.

Bonus One-Liner Method 5: List Comprehension

A one-liner approach uses list comprehension to create a list of boolean values indicating whether each pair is consecutive and then checks if all values are True.

Here’s an example:

queue = [4, 5, -2, -1, 10, 11]
print(all(abs(queue[i] - queue[i+1]) == 1 for i in range(0, len(queue) - 1, 2)))

Output: True

This concise one-liner uses a list comprehension within the all() function to check if the difference between every pair of elements is 1. It is a compact approach but assumes the queue is a list for indexing.


  • Method 1: Iterative Comparison. It is simple and does not require converting the queue. However, it may be slower due to individual get operations for each element.
  • Method 2: Using a List. Random access is a plus, but it requires additional space for the list and might not be suitable for large queues.
  • Method 3: Deque for In-Place Checking. This method is efficient for large data structures as it avoids copying. Nonetheless, it destructively consumes elements from the deque.
  • Method 4: Using Itertools. This approach is Pythonic and clean but requires familiarity with itertools. Inefficiency may arise for very large queues due to the conversion to a list before calling pairwise().
  • Bonus Method 5: List Comprehension. The most concise method. It leverages Python’s comprehensions elegantly but lacks readability for those who prefer step-by-step logic.