Stack Operations
In this section, we will discuss the most common operations associated with stacks: push, pop, and peek.
Push Operation
The push operation adds an element to the top of the stack. It increases the size of the stack by one and places the new element at the top.
In the implementation of a stack, the push operation can be performed using the append
method in Python or by using the push
method if a custom stack class is used.
Here is an example of how the push operation works:
1stack = []
2stack.append(1)
3stack.append(2)
4stack.append(3)
5
6print(stack) # Output: [1, 2, 3]
Pop Operation
The pop operation removes the element at the top of the stack and returns it. It decreases the size of the stack by one.
In the implementation of a stack, the pop operation can be performed using the pop
method in Python or by using the pop
method if a custom stack class is used.
Here is an example of how the pop operation works:
1stack = [1, 2, 3]
2
3print(stack.pop()) # Output: 3
4print(stack) # Output: [1, 2]
Peek Operation
The peek operation returns the element at the top of the stack without modifying the stack. It does not change the size of the stack.
In the implementation of a stack, the peek operation can be performed by accessing the last element of the stack in Python or by using the peek
method if a custom stack class is used.
Here is an example of how the peek operation works:
1stack = [1, 2, 3]
2
3print(stack[-1]) # Output: 3
4print(stack) # Output: [1, 2, 3]
It is important to note that performing the pop or peek operation on an empty stack will result in an error.
Now that we have a good understanding of the stack operations, let's move on to the next section where we will learn about queue operations.
xxxxxxxxxx
import numpy as np
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
average = total / len(numbers)
return average
numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print('Average:', average)