1
class Queue:
def __init__(self):
    self.items = []

def isEmpty(self):
    return self.items == []

def enqueue(self, item):
    self.items.append(item)

def dequeue(self):
    if self.items == []:
        raise IndexError('The queue is empty.')
    return self.items.pop()

def size(self):
    return len(self.items)

def __str__(self):
    return "Queue: " + (str(self.items))

def enqueue_list(self, list):
    for i in list:
        self.items.append(i)
    return self.items

def splice(self, second_queue):
    for i in second_queue:
        self.items.enqueue(i)
    return self.items

Hi there,

What I am trying to do is at the bottom in the splice method. I want to iterate through a second queue and add it to the end of the original one. I can't find out how I can iterate through a queue without causing an error however. Should I change second_queue into a list somehow first?

Original exception was:
Traceback (most recent call last):
File "prog.python3", line 74, in <module>
my_queue.splice(another_queue)
File "prog.python3", line 28, in splice
for i in second_queue:
TypeError: 'Queue' object is not iterable
verdy
  • 89
  • 1
  • 3
  • What error would that be? – timgeb Apr 29 '18 at 09:33
  • TypeError: 'Queue' object is not iterable – verdy Apr 29 '18 at 09:33
  • Ok, please add the complete traceback to your question and the code you are using to trigger it. http://idownvotedbecau.se/noexceptiondetails/ can be a helpful read, too. – timgeb Apr 29 '18 at 09:34
  • Original exception was: Traceback (most recent call last): File "prog.python3", line 74, in my_queue.splice(another_queue) File "prog.python3", line 28, in splice for i in second_queue: TypeError: 'Queue' object is not iterable – verdy Apr 29 '18 at 09:36
  • 1
    Ok, can you please edit that directly into the question? It is hard to read text that is supposed to be formatted in the comments. – timgeb Apr 29 '18 at 09:37
  • Ok but if you could tell me how to iterate through a queue and append it to another queue that would be great – verdy Apr 29 '18 at 09:40

1 Answers1

1

Instances of your class Queue are not iterable.

They hold a list items, but Python does not know that it should iterate over that list when you employ a for loop over a Queue instance.

To delegate the iteration to the wrapped list, simply add a method

def __iter__(self):
    return iter(self.items)

Demo with fixed class:

>>> q = Queue()
>>> q.enqueue(1)
>>> q.enqueue(2)
>>> q.items
[1, 2]
>>>
>>> for item in q:
...     print(item)
... 
1
2
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Defining `__getitem__` is another possibility. – Alex Hall Apr 29 '18 at 09:42
  • @AlexHall yes, but self-written classes should use `__iter__`. Read part 7 of [this answer](https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable/36407550#36407550). – timgeb Apr 29 '18 at 09:44