What is the specific method to iterate a stack in python. is the best practice to use a for loop just like to iterate a list?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As the others have said, python doesn’t really have a built-in stack datatype, per se– but you can use a list to emulate one.
When using a list as a stack, you can model the first-in-last-out behavior with append() as push and pop() as pop, as julio.alegria describes.
If you want to use that list in a for-loop, but still have it behave in the FILO fashion you can reverse the order of the elements with this slice syntax:
[::-1].Example:
If you’re using a custom class that implements a stack, just as long as it has
__iter__()andnext()methods defined you can use it in list comprehensions, for loops, or whatever.That way you can implement a custom iterator that removes items as it iterates over it, just as it should with a proper stack.
Example: