python-3.xdeque

appendleft iterating deque function, AttributeError: 'list' object has no attribute 'appendleft'


Ok, here's the code.

from collections import deque

list_stack = []
list_queue = ([])
string_to_list = "This is a sentence with more than six words."

string_to_list = string_to_list.split()

for i in string_to_list:
    list_stack.append(i)
    list_queue.appendleft(i)
print( "The variable created as a stack" ,list_stack)
print( "The variable created as a queue" ,list_queue)

The program should iterate through the variable string_to_list and then append the elements in the list to "list_stack" and to the first index in "list_queue". When I run the program it says: AttributeError: 'list' object has no attribute 'appendleft'. I'm not a very good programmer yet so its probably something simple that I'm missing. Multiple answers would be appreciated.


Solution

  • list_queue = ([])
    

    I'm guessing you intended this object to be a deque. If so, you have to be explicit in doing so:

    list_queue = deque()
    

    Note that a = [] and a = ([]) have identical behavior; they both create a list. The surrounding parentheses don't make a difference.