-4

How to reverse order the list containing strings where def view(self), because with reversed() I get an error that it can't be done with strings. Any help?

class Stack():

    def __init__(self):
        self.stack = []

    def view(self):
        for x in reversed(self.stack):
            print(self.stack[x])

    def push(self):
        item = input("Please enter the item you wish to add to the stack: ")
        self.stack.append(item)

    def pop(self):
        item = self.stack.pop(-1)
        print("You just removed item: {0}".format(item))

stack = Stack()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Martynas
  • 11
  • 1
  • 6
  • 1
    any reason you don't have simply `print(x)` in `view`? – John Coleman Mar 14 '16 at 12:12
  • "because with reversed() I get an error that it can't be done with strings. Any help? " No; you get an error that **indexing into** `self.stack` can't be done with strings - because `x` **is already** the string that you get by iterating in reverse. It's important to **read** and **try to understand** error messages, and to show [complete](https://meta.stackoverflow.com/questions/359146) error message when asking about them. – Karl Knechtel Sep 05 '22 at 11:18

1 Answers1

0

for x in list(...): sets x to each element of the list. You are might be confusing it with iterating over a dictionary, where x would be set to the key of each element.

def view(self):
    for x in reversed(self.stack):
        print(x)
Martin Valgur
  • 5,793
  • 1
  • 33
  • 45